uni-app, 小程序、app做环境国际化时,传递参数不生效
{
message: "操作{result}"
}
- $t('message', {result: '成功'})
- 期望输出结果为操作成功,实际上可能为 '操作{result}'
可以通过写一个方法根据 key, 当前语言去获取对应的语言文本
const isParamsObject = (obj, key) => {
return Object.prototype.toString.call(obj) === '[object Object]' && Object.keys(obj).length > 0 && Object.keys(obj).includes(key);
}
const interpolateTemplate = (template, values) => {
return template.replace(/{[A-Za-z\d]+}/g, (_, index) => values[_.slice(1, -1)] ?? '')
}
const originalT = i18n.global.t
i18n.global.t = ((key, param1, param2) => {
const result = originalT(key, param1, param2)
if (isParamsObject(param1, key)) {
return interpolateTemplate(result, param1)
}
return result
})