举例说明下面的用法 i18next
"key": "value",
"keyDeep": {
"inner": "value"
},
"keyNesting": "reuse $t(keyDeep.inner)",
"keyInterpolate": "replace this {{value}}",
"keyInterpolateUnescaped": "replace this {{- value}}",
"keyInterpolateWithFormatting": "replace this {{value, format}}",
"keyContext_male": "the male variant",
"keyContext_female": "the female variant",
"keyPluralSimple_one": "the singular",
"keyPluralSimple_other": "the plural",
"keyPluralMultipleEgArabic_zero": "the plural form 0",
"keyPluralMultipleEgArabic_one": "the plural form 1",
"keyPluralMultipleEgArabic_two": "the plural form 2",
"keyPluralMultipleEgArabic_few": "the plural form 3",
"keyPluralMultipleEgArabic_many": "the plural form 4",
"keyPluralMultipleEgArabic_other": "the plural form 5",
"keyWithArrayValue": ["multipe", "things"],
"keyWithObjectValue": { "valueA": "return this with valueB", "valueB": "more text" }
}
在这个例子中,你看到的是一个用于管理本地化文本的 i18next 配置对象。下面详细说明这些键的用法。
- "key": "value"
使用 t('key'),会返回 "value"
"keyDeep": { "inner": "value" }
使用 t('keyDeep.inner'),会返回 "value"
"keyNesting": "reuse $t(keyDeep.inner)"
使用 t('keyNesting'),会返回 "reuse value"。这里使用了嵌入式翻译参数$t。
"keyInterpolate": "replace this {{value}}"
使用 t('keyInterpolate', { value: 'example' }),会返回 "replace this example"。这里,{{value}} 被实际参数 'example' 替换。
"keyInterpolateUnescaped": "replace this {{- value}}"
与"keyInterpolate"类似,但会让值保留原样,不会对HTML进行转义
"keyInterpolateWithFormatting": "replace this {{value, format}}"
通过一种特定格式替换变量,format是一个自定义的格式函数。
"keyContext_male": "the male variant",
"keyContext_female": "the female variant"在略带条件的情况下,我们可以通过键后面的 "_male" 或 "_female" 来获取对应的值,如 t('keyContext', { context: 'male' }) 返回 "the male variant”。
"keyPluralSimple_one": "the singular",
"keyPluralSimple_other": "the plural"对于可数名词,我们可以使用复数,如 t('keyPluralSimple', { count: 1 }) 返回 "the singular",而 t('keyPluralSimple', { count: 2 }) 返回 "the plural"。
"keyWithArrayValue": ["multiple", "things"]
使用 t('keyWithArrayValue', { returnObjects: true }),会返回 ["multiple", "things"]
"keyWithObjectValue": { "valueA": "return this with valueB", "valueB": "more text" }
使用 t('keyWithObjectValue.valueA'),会返回 "return this with valueB"
i18next 是一个非常强大和灵活的本地化库,以上只是其功能的一小部分。你可以访问其官方文档详细了解这个库的所有功能。