node.js - Keystone.js + i18n。在渲染 View 之前获取当前区域设置

标签 node.js internationalization keystonejs

我正在尝试将 i18n 包含在 keystone.js 应用程序中。我这样做就像这个例子 https://gist.github.com/JedWatson/9191081 ,并且它有效,但我的问题是查看当前的区域设置。我正在使用中间件通过 url 参数设置区域设置:

// middleware.js
exports.setLocale = function (req, res, next) {
    if (req.params.lang) {
        req.setLocale(req.params.lang);
    }
    else
        res.redirect('/ru/');
    next();
};

// index.js
keystone.pre('render', middleware.setLocale);

和路由

app.get('/:lang/', routes.views.index);
app.get('/:lang/blog/:category?', routes.views.blog);
app.get('/:lang/blog/post/:post', routes.views.post);
...

默认区域设置为“ru”。但在我看来

view.on('render', function (next) {
    console.log('on render', req.getLocale());
    next();
});

console.log('before render', req.getLocale());
view.render('blog');

在路线/en/blog上输出

------------------------------------------------
KeystoneJS Started:
qalqan is ready on default port 3000
------------------------------------------------

before render ru
on render en
GET /en/blog 304 373ms

因此,据我了解,在变量发送到 View 后,区域设置发生了更改。有什么方法可以在渲染之前设置它吗?我知道,我可以通过每个 View 中的 url param lang 中的 req.params 获取它,但我想通过所有 View 的中间件来实现。

最佳答案

更新:从 i18n 版本 0.7.0 开始,您的代码应该可以工作。

这似乎有点违反直觉,但我认为你不应该碰路由以避免重复 lang 参数。

不过,您完全走在正确的道路上,这就是我所做的:

// routes/middleware.js

exports.detectLang = function(req, res, next) {
    var match = req.url.match(/^\/(de|en)([\/\?].*)?$/i);

    if (match) {
        req.setLocale(match[1]);
        // Make locale available in template
        // (necessary until i18n 0.6.x)
        res.locals.locale = req.getLocale();
        // reset the URL for routing
        req.url = match[2] || '/';
    } (else) {
        // Here you can redirect to default locale if you want
    }

    next();
}

现在只需在定义所有其他 res.locals 之前使用中间件即可:

// routes/index.js

keystone.pre('routes', i18n.init);
keystone.pre('routes', middleware.detectLang);

现在,您可以在所有 URL 前面添加 '/' + res.locals.locale,用户将在您的应用中的任何地方保留其区域设置。

关于node.js - Keystone.js + i18n。在渲染 View 之前获取当前区域设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28165007/

相关文章:

javascript - 由于先前的 Promise 已解决,因此未调用 Promise

javascript - Post请求在服务器端返回未定义

javascript - 功能未按顺序运行

ruby-on-rails - 说明如何使用 I18n.l @user.created_at,格式 : :default

email - 电子邮件地址可以包含国际(非英语)字符吗?

javascript - 如何在我的应用程序中使用 Keystone.js admin api(未经授权)?

node.js - 提高mongo查询性能

node.js - Nodejs PDF使下载无法打开

java - 如何更改 Struts2 中的默认日期格式?

node.js - 如何将 Keystone.JS 添加到现有 Express.js 应用程序?