i18next如何处理可变文本的替换和格式化?

i18next 里的数字等处理

在 i18next 中,可以通过插值来处理可变文本的替换和格式化。这种变量替换和格式化的方式非常灵活,并且能够支持同时处理多个变量。

对于简单的替换,只要在翻译字符串中用双大括号{{}}包围变量名,然后在调用翻译函数t()时,将模板变量作为第二个参数传入,i18next 会使用提供的值自动替换文本中的模板变量:

i18n.t('keyInterpolate', { value: 'example' });

如果翻译字符串为"replace this {{value}}",以上代码会得到"replace this example"

在默认情况下,插入的变量值会被转义,避免可能的 XSS 攻击。如果你想要插入的变量值保持原样,不被转义,可以在变量名前加 -

i18n.t('keyInterpolateUnescaped', { value: '<img src="attack.jpg">' });

如果翻译字符串为"replace this {{- value}}",以上代码会得到"replace this <img src='attack.jpg'>"

对于数字的格式化,你还可以使用 Intl.NumberFormat 对象(需要浏览器或环境支持),在选项对象中新增一个 format 函数:

const format = function(value) {
    return new Intl.NumberFormat('en-US').format(value);
  };

i18n.t('keyInterpolateWithFormatting', { value: 1234567, format });

假设翻译字符串为"Here is your formatted number: {{value, format}}",以上的代码会得到"Here is your formatted number: 1,234,567"