i18next的t函数是否支持复数?需在代码内实现英文复数翻译
解决代码内维护翻译时的复数格式问题
问题原因
你之前的写法无效,是因为t函数的第一个参数是翻译键(asd),而你没有为这个键配置对应的复数翻译条目,同时参数中的one/other并非t函数的标准解析参数,所以函数直接输出了键值asd。
可行解决方案
方案1:直接通过JS条件判断(最简单)
无需依赖翻译库的复数功能,直接根据count的值选择对应的翻译字符串:
const count = getSuppliersCount(); const msg = count === 1 ? t('We found {{count}} supplier', { count }) : t('We found {{count}} suppliers', { count }); console.log(msg);
方案2:利用翻译库的内联复数语法(如果支持)
如果你的t函数支持内联复数解析(比如i18next),可以在defaultValue中使用复数语法直接定义规则,无需外部locale文件:
const count = getSuppliersCount(); console.log(t('suppliers_found', { count, defaultValue: 'We found {{count}} {{count, plural, one {supplier} other {suppliers}}}' }));
方案3:动态添加复数翻译条目(如果库支持)
如果你的翻译库允许在代码中直接注册翻译资源(无需外部文件),可以提前添加复数条目后再调用t函数:
// 以i18next为例,动态添加英文复数翻译 i18next.addResource('en', 'translation', 'suppliersFound', { one: 'We found {{count}} supplier', other: 'We found {{count}} suppliers' }); // 使用时 const count = getSuppliersCount(); console.log(t('suppliersFound', { count }));
内容的提问来源于stack exchange,提问作者Onkeltem
相关产品推荐
相关产品推荐

