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

问题描述 投票:0回答:2

我想在我的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/恩.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变量。

我该如何解决我的问题?

node.js express internationalization underscore.js ejs
2个回答
1
投票

来自docs:

通常,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);

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

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

0
投票

这是我的解决方案。

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();
};

其他文件与您相同。

希望对你有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.