将语言参数传递给jade链接

时间:2016-08-17 22:14:10

标签: node.js internationalization pug

我有一个多语言网站,在超链接中使用语言标识符,例如英文联系页面的/ en / contact和德语联系页面的/ de / contact。

如果我在我的页面上交叉链接,例如从索引页面到联系页面,我如何在我的超链接中“传递”语言部分?根据我是在/ en / index还是在/ de / index上,超链接需要指向/ en / contact或/ de / contact。

我正在使用Express + Jade。 两种语言都有一个玉模板需要动态设置链接,具体取决于用户是在/ en还是/ de页面。

提前多多感谢!

2 个答案:

答案 0 :(得分:1)

这是我能想到的最简单的例子。使用中间件功能检查请求并提取语言,然后将其设置为可用于模板的变量。您可以使用更多的全局中间件,但此示例在单个路径上显示它:

app.use('/:userLang/contact', i8n, users);

function i8n(req, res, next) {
  var supportedLanguages = ['en', 'de'];
  var defaultLang = 'en';
  var pathLang = req.params.userLang;

  // default to en if a user trys a language that isn't supported
  // another(possibly better) option would be to 404 or 301 to the en version
  res.locals.userLang = (supportedLanguages.indexOf(pathLang) > -1) 
                          ? req.params.userLang : defaultLang;
  next();
}

完成上述代码后,模板中的链接可能如下所示:

a(href="/#{userLang}/contact) Contact Page

答案 1 :(得分:0)

在联系页面,您可以将用户发送到英文索引页面,假设您在英文联系页面

a(href="/en/index")
相关问题