如何在节点和i18n上使用多语言路由?

时间:2017-01-07 20:12:25

标签: node.js express internationalization multilingual

我正在建立一个简单的网站,并希望翻译链接。

例如:

  • about-us / a-propos-de-nous

目前,我注意到要使用i18n设置语言,您需要重定向用户,以便通过执行以下操作来抓住用户:

app.get('/fr', (req, res) => {
    i18n.setLocale('fr');
    res.cookie('i18n', 'fr');
    res.redirect('/');
});

但是,如果用户直接访问以下网址,该怎么办?

app.get(['/about-us', '/a-propos-de-nous'], (req, res) => {
    // How do I set the proper locale here? I can't do any redirect otherwise
    // I'll be caught in a redirect loop.
    res.render('about-us');
});

1 个答案:

答案 0 :(得分:0)

您可以从req.url获取请求的路径,您可以检查它是哪一个并相应地设置语言。

app.get(['/about-us', '/a-propos-de-nous'], (req, res) => {
  if(req.url === '/about-us') {
    i18n.setLocale('en');
    res.cookie('i18n', 'en');
  } else if(req.url === '/a-propos-de-nous') {
    i18n.setLocale('fr');
    res.cookie('i18n', 'fr');
  }

  res.render('about-us');
});

您还可以在example.com/fr/a-propos-de-nous之类的路径前添加前缀,这样可以更轻松地从请求中提取语言。

相关问题