我正在使用Node JS Azure功能。我试图用i18next国际化函数返回的错误消息。我可以找到快速或普通节点服务器的例子。在这些情况下,可以使用中间件模式。
但是对于函数,我需要一种方法来调用i18next.t('key')可能是一个我无法找到的语言参数。在每次调用i18next.t('key')之前调用i18next.changeLanguage()似乎不实用。
我的骨架代码如下
const i18next = require("i18next");
const backend = require("i18next-node-fs-backend");
const options = {
// path where resources get loaded from
loadPath: '../locales/{{lng}}/{{ns}}.json',
// path to post missing resources
addPath: '../locales/{{lng}}/{{ns}}.missing.json',
// jsonIndent to use when storing json files
jsonIndent: 4
};
i18next.use(backend).init(options);
exports.getString = (key, lang) => {
//i18next.changeLanguage(lang,
return i18next.t(key);
}
每次都可以在不进行changeLanguage的情况下获取翻译?
正如评论中所指出的,只要需要定义或更改语言,就需要调用i18next.changeLanguage(lang)
函数。
你可以看看documentation here。
代码看起来像这样
const i18next = require('i18next')
const backend = require('i18next-node-fs-backend')
const options = {
// path where resources get loaded from
loadPath: '../locales/{{lng}}/{{ns}}.json',
// path to post missing resources
addPath: '../locales/{{lng}}/{{ns}}.missing.json',
// jsonIndent to use when storing json files
jsonIndent: 4
}
i18next.use(backend).init(options)
exports.getString = (key, lang) => {
return i18next
.changeLanguage(lang)
.then((t) => {
t(key) // -> same as i18next.t
})
}