Symfony 4 支持按 Bundle 分开管理翻译资源,关键是在 translation.yaml 中配置 translator.paths 添加 Bundle 的 Resources/translations 路径,并严格遵循 domain.locale.loader 命名规则(如 messages.en.yaml);调用时须显式指定 domain,提取时需用 --dir 指定 Bundle 目录。

Symfony 4 支持按 Bundle 分开管理翻译资源,关键在于路径配置与文件命名规则的配合。默认只扫描 translations/ 目录,但只要在配置中显式添加 Bundle 对应的翻译路径,并遵守 domain + locale + loader 的命名约定,就能实现各 Bundle 独立维护自己的语言包。
Bundle 翻译目录结构怎么放
每个 Bundle 可在自身目录下建 Resources/translations/(Symfony 4 标准路径),例如:
src/UserBundle/Resources/translations/messages.en.yamlsrc/UserBundle/Resources/translations/validators.zh_CN.xlfsrc/AdminBundle/Resources/translations/messages.fr.yaml
文件名必须含 domain(如 messages、validators)、locale(如 en、zh_CN)和扩展名(如 .yaml、.xlf),Symfony 才能自动识别 domain 和 locale。
怎么让 Symfony 扫描 Bundle 里的翻译文件
修改 config/packages/translation.yaml,把 Bundle 的翻译路径加进 translator.paths 列表:
framework:
translator:
paths:
- '%kernel.project_dir%/translations'
- '%kernel.project_dir%/src/UserBundle/Resources/translations'
- '%kernel.project_dir%/src/AdminBundle/Resources/translations'
路径顺序决定优先级:排在前面的同名 domain+locale 文件会覆盖后面的。比如两个 messages.en.yaml,UserBundle 的会优先生效。
代码里调用时要不要指定 domain
要。Bundle 内部使用的 domain 由文件名决定,但调用时仍需明确传参:
- 控制器中:
$translator->trans('login.title', [], 'messages')(若来自 UserBundle 的 messages.en.yaml) - Twig 模板中:
{{ 'login.title'|trans({}, 'messages') }}或{% trans from 'validators' %}password_too_short{% endtrans %}
不传 domain 默认走 messages,但无法区分是主项目还是哪个 Bundle 提供的 —— 所以显式声明更安全、更清晰。
提取翻译键值要注意什么
运行 php bin/console translation:extract en --force 时,默认只扫 translations/。若要提取 Bundle 内的 PHP/Twig 文件中的翻译,得加上 --dir 参数:
php bin/console translation:extract en --dir=src/UserBundle --forcephp bin/console translation:extract zh_CN --dir=src/AdminBundle --force
提取结果默认写入 translations/,如需写进 Bundle 自己的目录,可用 --output-dir 指定,例如:--output-dir=src/UserBundle/Resources/translations。


















