【问题标题】:Node js permanently locale changesNode js 永久更改语言环境
【发布时间】:2016-08-09 10:03:16
【问题描述】:

我正在使用 Expressjs 和 i18n 为我的节点 js 应用程序来管理多语言。

这是我的 i18n 配置:

i18n.js

var i18n = require('i18n');

i18n.configure({

  locales:['en', 'fr'],

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

server.js

var i18n = require('./configs/i18n');
 ...

app.use(i18n);

实际上,如果我想更改区域设置,我必须为每条路线都这样做:

app.get('/index', function(req, res){
    res.setLocale('fr')

    res.render('pages/index');
});

可以使用setLocale() 一次,它会永久更改语言环境?

什么是最佳实践?我应该每次都在我的路线中指定语言吗?例如:

app.get('/:locale/index', function(req, res){
    res.setLocale(req.params.locale)

    res.render('pages/index');
});

app.get('/:locale/anotherroute', function(req, res){
    res.setLocale(req.params.locale)

    res.render('pages/anotherroute');
});

或者我必须将每个用户的语言环境存储在我的数据库中?

【问题讨论】:

    标签: node.js internationalization


    【解决方案1】:

    您可以使用middlewares 来避免重复(将此代码放在您的路由器之前):

    // Fixed locale
    app.use(function (req, res, next) {
      res.setLocale('fr');
      next();
    });
    
    // Locale get by URL parameters
    app.use(function (req, res, next) {
      if (req.params && req.params.locale){
          res.setLocale(req.params.locale);
      }
      next();
    });
    

    就个人而言,我更喜欢将本地设置存储在数据库中,这样可以避免用不必要的数据来衡量请求。

    另一种解决方案是用Content-LanguageAccept-Language设置HTTP头的语言,用req.acceptsLanguage()获取。

    【讨论】:

    • 感谢您的回答。我得到无法读取未定义的属性“语言环境”?这是否意味着我应该为每条路线指定语言环境参数?app.get('/:locale/index', function(req, res)
    • 我更新了帖子,修复了错误,并添加了基于 HTTP 标头和 acceptsLanguage() 函数的更好解决方案。我希望它能回答你的问题。
    • 好的,谢谢。因此,如果我想将语言存储在我的数据库中,我只需在您的固定语言环境中间件函数中执行 mongoDB 查询,或者使用我的 passportJS 用户会话变量获取它?
    • 没错!我认为在登录时获取语言环境并将其存储在req.session 中是个好主意。
    • 不错不错。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多