我正在使用react-intl及其<FormattedMessage />
标签。
我想拥有一条结构化的消息,该消息将根据提供的值选择正确的复数变体,以允许翻译人员使用其语言规则,即,如果他们对“一个”,“两个”,“许多”有不同的变体“,项目等。我不希望通过switch
语句将其硬编码在应用程序业务逻辑中,而该语句仅将英文规则用于“零”,“一个”和“其他”。
<FormattedMessage id="myMessage" values={{applesCount: 4, orangesCount: 0, pearsCount: 1}} />
应从以下来源生成I have some apples and some pears
。
由于某些原因,它返回I have some apples, some pears, and some oranges
{applesCount, plural,
zero {{pearsCount, plural,
zero {{orangesCount, plural,
zero {I have no fruit}
other {I have some oranges}
}}
other {{orangesCount, plural,
zero {I have some pears}
other {I have some pears and some oranges}
}}
}}
other {{pearsCount, plural,
zero {{orangesCount, plural,
zero {I have some apples}
other {I have some apples and some oranges}
}}
other {{orangesCount, plural,
zero {I have some apples and some pears}
other {I have some apples, some pears, and some oranges}
}}
}}
}
我通过https://format-message.github.io/icu-message-format-for-translators/editor.html对其进行了测试
此外,我还有此代码和框,您可以在其中进行修改:https://codesandbox.io/s/react-intl-formattedmessage-using-plural-x8ki5
作为参考,我检查了http://userguide.icu-project.org/formatparse/messages和https://formatjs.io/guides/message-syntax/,并希望支持我的消息结构。
您能帮我检测出什么地方出了问题,还是应该改变它以使其正常工作?
问题是:
英语作为一种语言没有专门针对零个项目的语法。
主要是单数或复数(在一些罕见的残差情况下dual)。
您正在使用的语法专门针对那些语法专门针对零个项目的语言。 (例如阿拉伯语和拉脱维亚语)
阅读此处:https://formatjs.io/guides/message-syntax/#plural-format。此外,wikipedia上的这篇文章也对此进行了解释
因此,该方法不适用于英语。相反,您需要使用=0
(=值语法)将数量匹配为零才能使解决方案起作用。
{applesCount, plural,
=0 {{pearsCount, plural,
=0 {{orangesCount, plural,
=0 {I have no fruit}
other {I have some oranges}
}}
other {{orangesCount, plural,
=0 {I have some pears}
other {I have some pears and some oranges}
}}
}}
other {{pearsCount, plural,
=0 {{orangesCount, plural,
=0 {I have some apples}
other {I have some apples and some oranges}
}}
other {{orangesCount, plural,
=0 {I have some apples and some pears}
other {I have some apples, some pears, and some oranges}
}}
}}
}
类似地,对于1个数字,one
不适用于英语。您必须使用=value
语法(=1
)。在sandbox上进行了尝试,效果很好。
希望有帮助。如有任何疑问,请回复。