【发布时间】:2016-02-15 20:21:34
【问题描述】:
我为 Express JS 构建了一个非常简单的翻译模块,它是应用程序范围内的一个全局对象,在应用程序运行时被实例化:
translator.configure({
translations: 'translations.json'
});
我在 Express JS 中添加了一些简单的中间件,可以为每个请求更改翻译模块中的语言环境:
app.use(function(req, res, next) {
var locale = // Get locale from request host header
// Setup the translator
translator.setLocale(locale);
// Attach translator to request parameters
res.locals.__ = translator.translations;
// Pass control to the next middleware function
next();
});
然后我通过我的视图中的变量__ 访问我的翻译(这里我使用ejs):
...
Here is my translated text: <%= __['test'] %>
...
我的翻译模块如下所示:
var translations,
locale;
// public exports
var translator = exports;
translator.configure = function(opt) {
translations = require('./' + opt.translations);
};
translator.setLocale = function(locale) {
translator.translations = translations[locale];
}
translations.json 文件只是一个简单的 JSON 结构:
{
"us":{
"test": "Hello!"
},
"es":{
"test": "Hola!"
}
}
我的问题是,这种整体结构是个坏主意吗?我对 express JS 没有广泛的了解。全局对象让我有点紧张,因为翻译是基于它的当前状态,从请求到请求都会改变,这里有什么问题吗? express JS 是否在处理下一个请求之前完全完成了一个请求,或者是否存在某种程度的并发会弄乱我的翻译?
【问题讨论】:
-
@stdob-- 谢谢,但这基本上是我基于我自己的代码的模块。我认为这个模块对于我的目的来说看起来有点矫枉过正,我需要一些比这更灵活的东西。
标签: javascript json node.js express internationalization