【发布时间】:2025-12-01 02:05:02
【问题描述】:
我想在我的 express (nodejs) 中实现多语言 但是我不明白为什么我的 ejs 不理解“__”下划线。
app.js
var i18n = require('./i18n');
app.use(i18n);
i18n.js
var i18n = require('i18n');
i18n.configure({
locales:['fr', 'en'],
directory: __dirname + '/locales',
defaultLocale: 'en',
cookie: 'lang'
});
module.exports = function(req, res, next) {
i18n.init(req, res);
res.locals.__ = res.__;
var current_locale = i18n.getLocale();
return next();
};
路由器.js
console.log(res.__('hello')); // print ok
console.log(res.__('helloWithHTML')); // print ok
req.app.render('index', context, function(err, html) {
res.writeHead('200', {'Content-Type':'text/html;charset=utf8'});
res.end(html);
});
/locales/en.json
{
"hello": "Hello.",
"helloWithHTML": "helloWithHTML."
}
index.ejs
<%= __("hello")%>
我收到了一条错误消息:
__ is not defined at eval (eval at compile (/home/nodejs/node_modules/ejs/lib/ejs.js:618:12), :41:7) at returnedFn
但是我可以看到来自路由器的日志消息:
console.log(res.__('hello')); // print out Hello
console.log(res.__('helloWithHTML')); // print out helloWithHTML
它工作正常,我可以看到 hello 和 helloWithHTML 值。
但是ejs 根本无法识别i18n 变量。
如何解决我的问题?
【问题讨论】:
-
对我来说,看起来你的中间件不是针刺的。可以改写成
module.export = i18n,然后在app.js里面写app.use(i18n.init);,就是为了简化,不知道现在的代码哪里出了问题。 -
@Starke 如果我放 app.use(i18n.init) 是相同的结果 :( 我需要弄清楚为什么这个问题会发生在我身上。奇怪的是 console.log(res.__('hello ')) 工作正常,所以我认为它与 ejs 或其他任何东西有关..
-
是的,我也这么认为,
req.app.render('index')对我来说有点奇怪,通常它只是res.render('index'); -
我通常用中间件渲染。我还将我的应用设置为这样 app.set('view engine', 'ejs');
标签: node.js express internationalization underscore.js ejs