Symfony 4 通过 translation:extract 命令扫描代码提取翻译字符串并生成 XLIFF/YAML 等格式文件,需确保 symfony/translation 已安装、translator 已启用、translations 目录存在且有读写权限。

Symfony 4 中没有内置命令能“自动生成翻译文件”,但可通过 translation:extract 命令扫描代码,提取待翻译的字符串并写入指定格式的翻译资源文件——这是生成本地化翻译文件最标准、最实用的方式。
确保翻译组件已启用并配置路径
若命令执行失败或提示“command not found”,说明 symfony/translation 未正确安装或未启用。需确认:
- 已运行
composer require symfony/translation -
config/packages/translation.yaml中启用了 translator,并设置了default_path(如'%kernel.project_dir%/translations') - 项目根目录下存在
translations/目录,且 Web 服务器有读写权限
用 translation:extract 扫描并生成基础文件
该命令会自动查找代码中所有 $translator->trans()、$this->trans()、Twig 的 {{ 'key'|trans }} 等调用,提取源字符串。
- 生成英文基础文件(推荐作为源语言):
php bin/console translation:extract en --output-format=xlf --domain=messages - 生成法语占位文件(不覆盖已有翻译):
php bin/console translation:extract fr --output-format=xlf --domain=messages --keep - 扫描特定目录(如跳过测试):
php bin/console translation:extract en --dir=src/Controller --dir=src/Repository
注意:--keep 参数很重要——它保留已有翻译,只新增未出现的 key;不加则清空重写,容易丢失人工维护内容。
支持多格式与自定义域
命令默认输出 XLIFF(.xlf),但可灵活切换:
- 输出 YAML:
php bin/console translation:extract zh_CN --output-format=yml --domain=admin
(需先启用symfony/yaml并在translation.yaml中注册yml加载器) - 提取验证器消息(
validators域):php bin/console translation:extract en --domain=validators - 合并多个域到一个命令:
php bin/console translation:extract en --domain=messages --domain=validators
常见问题与绕过技巧
命令无法识别某些动态 key(如拼接字符串、变量传入),这时需手动补充:
- 在代码中添加注释标记,引导提取器识别:
// @translate "User not found" - 对 Twig 模板中未被扫描到的字符串,可临时改写为
{{ 'User not found'|trans }}再运行 extract - 若提示 “No files were processed”,检查是否遗漏
--dir或路径权限;也可加--debug查看扫描详情


















