我正在尝试建立一个多语言的网站。我决定使用数据对象,以填写所有必需的文本。我使用的两种语言的路由完全相同,只是导入有所不同。没有代码重复,有什么方法可以做到这一点?
模板引擎是Express Handlebars,因此,如果有另一种使网站成为多语言的解决方案,我愿意实现它:) 在此先感谢您抽出宝贵的时间阅读本文。
我的路线中使用Sl语言的代码:
const express = require("express"),
router = express.Router(),
data = require("../Views/res/lang/sl");
router.get("/", (req, res) => {
data.Home = setupDataObject(data.Home, req.originalUrl, "Home");
res.render("homepage", data.Home);
});
router.get("/About", (req, res) => {
data.About = setupDataObject(data.About, req.originalUrl, "About");
res.render("About", data.About);
});
function setupDataObject(data, url, active) {
data.current = url.substring(4);
data.active = { [active]: true };
return data;
}
module.exports = router;
还有英文版
const express = require("express"),
router = express.Router(),
data = require("../Views/res/lang/en");
router.get("/", (req, res) => {
data.Home = setupDataObject(data.Home, req.originalUrl, "Home");
res.render("homepage", data.Home);
});
router.get("/About", (req, res) => {
data.About = setupDataObject(data.About, req.originalUrl, "About");
res.render("About", data.About);
});
function setupDataObject(data, url, active) {
data.current = url.substring(4);
data.active = { [active]: true };
return data;
}
module.exports = router;
答案 0 :(得分:1)
您可以使用url参数来处理语言环境,不是吗?
const express = require("express"),
router = express.Router();
router.get("/:locale/", (req, res) => {
const data = require("../Views/res/lang/" + locale);
data.Home = setupDataObject(data.Home, req.originalUrl, "Home");
res.render("homepage", data.Home);
});
router.get("/:locale/About", (req, res) => {
const data = require("../Views/res/lang/" + locale);
data.About = setupDataObject(data.About, req.originalUrl, "About");
res.render("About", data.About);
});
function setupDataObject(data, url, active) {
data.current = url.substring(4);
data.active = { [active]: true };
return data;
}
module.exports = router;