Ric*_*ard 4 internationalization ejs node.js express underscore.js
我想在我的express(nodejs)中实现多语言但是我无法理解为什么我的ejs不理解“__”下划线。
应用程序.js
var i18n = require('./i18n');
app.use(i18n);
Run Code Online (Sandbox Code Playgroud)
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();
};
Run Code Online (Sandbox Code Playgroud)
路由器.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);
});
Run Code Online (Sandbox Code Playgroud)
/locales/en.json
{
"hello": "Hello.",
"helloWithHTML": "helloWithHTML."
}
Run Code Online (Sandbox Code Playgroud)
索引.ejs
<%= __("hello")%>
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息:
__ is not defined at eval (eval at compile (/home/nodejs/node_modules/ejs/lib/ejs.js:618:12), :41:7) at returnedFn
Run Code Online (Sandbox Code Playgroud)
但是我可以看到来自路由器的日志消息:
console.log(res.__('hello')); // print out Hello
console.log(res.__('helloWithHTML')); // print out helloWithHTML
Run Code Online (Sandbox Code Playgroud)
它工作正常,我可以看到hello和helloWithHTML值。
但根本ejs不识别变量。i18n
我该如何解决我的问题?
来自文档:
一般来说,i18n 必须附加到响应对象,以便在模板和方法中可以访问它的公共 api。从 0.4.0 开始,i18n 尝试通过 i18n.init 在内部执行此操作,就像您自己在 app.configure 中执行此操作一样
因此,您可以使用的最简单的方法是:
// i18nHelper.js file <-- you may want to rename the file so it's different from node_modules file
var i18n = require('i18n');
i18n.configure({
locales:['fr', 'en'],
directory: __dirname + '/locales',
defaultLocale: 'en',
cookie: 'lang'
});
module.export = i18n
// app.js
const i18n = require('./i18nHelper.js');
app.use(i18n.init);
Run Code Online (Sandbox Code Playgroud)
或者如果你真的想绑定(自己):
// somei18n.js
module.exports = function(req, res, next) {
res.locals.__ = i18n.__;
return next();
};
// app.js
const i18nHelper = require('./somei18n.js')
app.use(i18nHelper);
app.get('/somepath', (req, res) => {
res.render('index');
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7386 次 |
| 最近记录: |