nodejs i18n __ 不是 ejs 的函数问题,express

nodejs i18n __ is not a function issue with ejs, express

我想在我的 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();
};

router.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

工作正常,我可以看到 hellohelloWithHTML 值。

但是ejs根本不识别i18n变量。

如何解决我的问题?

来自文档:

In general i18n has to be attached to the response object to let it's public api get accessible in your templates and methods. As of 0.4.0 i18n tries to do so internally via i18n.init, as if you were doing it in app.configure on your own

所以,您可以使用的最简单的方法是:

// 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);

或者如果你真的想绑定(自己绑定):

// 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');
})

这是我的解决方案。

i18n.js

var i18n = require('i18n');

i18n.configure({
  locales: ['zh_CN', 'en'],
  directory: __dirname+'/locales'
});

module.exports = function(req, res, next) {
  let {lang} = req.query;
  i18n.init(req, res);
  lang = lang ? lang : 'zh_CN';
  i18n.setLocale(req, lang);
  return next();
};

其他文件和你一样

希望对您有所帮助。