实现此功能的一种方法是使用i18next的backend模块。我们可以在后端定义一个变量对象,其中包含默认插值变量,并将其作为翻译的一部分发送到前端。在前端,我们可以使用i18next的interpolate函数,将传递给翻译函数的参数与默认变量合并,得到最终插值结果。
以下是一个示例:
后端代码:
const i18next = require('i18next');
const backend = require('i18next-fs-backend');
//设置后端
i18next.use(backend).init({
backend: {
loadPath: 'locales/{{lng}}/{{ns}}.json', //翻译文件的路径
//自定义变量对象
interpolate: {
//默认变量
defaultValue: {
name: 'John',
age: 30,
},
},
},
});
//发送翻译结果给前端
app.get('/translate', (req, res) => {
const translation = i18next.t('myKey', { returnObjects: true });
res.json(translation);
});
翻译文件locales/en/translation.json:
{
"myKey": "Hi {{name}}, your age is {{age}}."
}
前端代码:
import i18next from 'i18next';
//初始化i18next
i18next.init({
lng: 'en',
resources: {
en: {
translation: require('./locales/en/translation.json'),
},
},
});
//调用i18next的翻译函数并传递参数
const name = 'Mike';
const age = 25;
const translation = i18next.t('myKey', { name, age });
//输出翻译结果
console.log(translation); // Hi Mike, your age is 25.
在此示例中,我们定义了一个默认插值变量对象,并将其作为