理解 i18next 的复数键?

问题描述 投票:0回答:1

我正在致力于将 i18next 集成到一个 React 项目中,使用react-18next,并使用 i18next-parser 生成带有当前翻译字符串的 JSON 文件,并使用自然语言键。

在我的源代码中,我有类似的内容:

<p>{t('{{count}} Sensors', { count: getSensorCount() })}</p>

其中

getSensorCount()
返回一个数字。

我的 i18next-parser 配置如下:

{
  locales: ['en', 'fr', 'es'],
  output: 'src/locales/$LOCALE/$NAMESPACE.json',
  defaultValue: (locale, namespace, key, value) => value || key,
  keySeparator: false,
  namespaceSeparator: false,
  verbose: true,
  createOldCatalogs: false
}

运行解析器会生成一个 JSON 文件,其键如下:

{
...
  "{{count}} Sensors_one": "{{count}} Sensors",
  "{{count}} Sensors_other": "{{count}} Sensors",
...
}

然后我将 Sensors_one 的值更改为

{{count}} Sensor

我希望当

count
为 1 时返回“1 Sensor”。这也是 i18next 文档描述复数工作方式的方式。

但是,它只是返回密钥,并且似乎无法在 JSON 文件中找到翻译。

让它返回正确值的唯一方法是像这样更改键:

  "{{count}} Sensors": "{{count}} Sensor",
  "{{count}} Sensors_plural": "{{count}} Sensors",

我想知道复数键的正确语法是什么,并且

如果是

key_one
key_other
,我如何才能让我的项目认识到这一点

如果是

key
key_plural
,我如何让我的 i18next-parser 配置使用正确的键生成 JSON 文件。

我的软件包版本如下:

"i18next": "^20.6.1",
"i18next-parser": "^8.0.0",
"react-i18next": "^13.0.0",
"react": "^18.2.0",

谢谢你。

编辑:Codesandbox 示例: https://codesandbox.io/s/react-i18next-forked-l5t9ws?file=/src/app.js

reactjs translation i18next react-i18next
1个回答
2
投票

在 i18next 的 version 21.0.0 中,他们更改了 json 文件中复数的写入方式。在 21 之前,就像在您的沙箱中一样,正确的方法是“foo_plural”。 21之后就是“foo_other”。进行此更改是为了使用与 javascript 使用的 Intl feature 相同的术语。

所以显然你正在使用新版本的 i18next-parser,但是旧版本的 i18next。可能的解决方案包括:

  1. 切换到新版本的i18next
  2. 切换到旧版本的 i18next-parser(我不确定具体是什么版本)
  3. option 传递到 i18next-parser 中,告诉它以旧方式解析复数:
{
  i18nextOptions: {
    compatibilityJSON: 'v3'
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.