Symfony 4 的 translation:extract 命令默认不提取 Twig 模板中的翻译字符串,需手动启用 twig 提取器、指定 --format=xlf 和 --dir=templates 才能完整生成符合众包平台要求的 XLIFF 文件。

Symfony 4 的 translation:extract 命令默认只扫描 PHP 文件里的 trans()、transChoice() 等调用,不会自动识别 Twig 模板中的翻译字符串,比如 {{ 'hello'|trans }} 或 {% trans %}Welcome{% endtrans %}。如果不做额外配置,直接运行命令会漏掉所有模板内容,导致本地化模板(如 messages.en.xlf)不完整——这是实际项目中最常见的提取失败原因。
确保 Twig 提取器已启用
Symfony 默认不加载 Twig 字符串提取器,必须手动激活:
- 确认已安装
symfony/twig-bridge(它提供TwigExtractor):composer require symfony/twig-bridge - 在
config/packages/translation.yaml中显式声明 extractor:framework:<br> translator:<br> extractors: ['twig']
- 注意:仅启用 extractor 不够,后续命令仍需配合格式与路径参数才能生效
必须使用 XLIFF 格式并指定模板目录
Twig 提取功能仅支持 --format=xlf,其他格式(如 yaml、php)会跳过 Twig 内容:
- 运行命令时务必加上
--format=xlf - 用
--dir=templates显式指向 Twig 模板根目录(不是src/或src/templates) - 典型命令示例:
php bin/console translation:extract en --dir=templates --format=xlf --output-dir=translations - 若项目同时含 PHP 和 Twig 翻译源,建议分两次执行:先扫
src/(PHP),再扫templates/(Twig)
检查生成的 XLIFF 文件是否符合众包要求
生成的 .xlf 文件需满足协作平台(如 Crowdin、Weblate)导入规范:
-
<file source-language="en">中的source-language必须正确设置,否则平台可能拒绝导入 -
<source>标签内应为键名(如user.email),而非原始文本;若看到原文,说明 extractor 未生效或路径配置错误 -
id属性由 Symfony 自动生成,切勿手动修改,否则合并翻译时会出错 - 如需添加上下文注释(提升翻译准确性),可在 Twig 中写成:
{{ 'user.email'|trans }} {# Email address shown in profile page #}
不复杂但容易忽略


















