Symfony 4.2+ 已移除 transchoice 过滤器,须改用 trans 过滤器配合 ICU 复数语法:翻译文件中写 ICU 格式,模板传参键名为 %count%,并确保 translation 组件启用且 locale 有效。

在 Symfony 4 中,transchoice 过滤器已**被弃用并移除**,取而代之的是统一使用 trans 过滤器配合复数规则(pluralization)语法。这是从 Symfony 4.2 开始的变更,官方明确要求用 {{ 'message'|trans({'%count%': count}) }} 替代旧式 transchoice 调用。
为什么不能用 transchoice?
Symfony 4.2+ 彻底移除了 transchoice Twig 过滤器和对应方法。如果你在模板中写 {{ 'app.items'|transchoice(3) }},Twig 会报错:Unknown "transchoice" filter。这不是配置问题,而是核心功能已被删除。
正确实现复数翻译的三步法
必须同时满足以下三点,复数才能正常工作:
-
翻译文件中使用 ICU MessageFormat 语法:在
translations/messages.en.yaml中写成:app.items: '{count, plural, =0{No items} =1{One item} one{# item} other{# items}}' -
模板中传入带
count键的参数数组:{{ 'app.items'|trans({'%count%': 5}) }}—— 注意键名必须是%count%(不是count),且值为整数 -
确保 translation 组件启用且 locale 设置有效:检查
config/packages/translation.yaml含framework.translator: { enabled: true, default_locale: 'en' };同时确认当前请求的 locale 是支持复数规则的语言(如en、fr、zh等)
常见错误与修复示例
❌ 错误写法:{{ 'app.items'|trans({'count': 2}) }} → 键名没加百分号,ICU 不识别
✅ 正确:{{ 'app.items'|trans({'%count%': 2}) }}
❌ 错误写法:app.items: 'You have %count% item(s)' → 没用 ICU 语法,永远不触发复数逻辑
✅ 正确:app.items: '{count, plural, =1{You have one item} other{You have # items}}'
⚠️ 注意:# 在 ICU 中自动替换为数字值,=1 表示精确匹配,one 和 other 是语言预定义的复数类别(不同 locale 类别数不同,如俄语有 four、many 等)
中文复数处理的特殊说明
中文没有语法性复数变化,但 ICU 仍要求提供 other 分支。可简化写作:app.items: '{count, plural, =0{暂无项目} =1{一个项目} other{# 个项目}}'
此时 %count% 值为 0、1、2… 都会进入对应分支,# 自动渲染为数字。


















