我正在使用 Node JS Azure 函数。我正在尝试使用 i18next 将函数返回的错误消息国际化。我可以找到快速或普通 Node 服务器的示例。在这些情况下可以使用中间件模式。
但是对于函数,我需要一种方法来调用 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
})
}
关于node.js - 如何在无服务器 Node js中使用i18next?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51230088/