Symfony中如何翻译实体的Enum类型属性?
Symfony枚举类型的Twig翻译解决方案
针对你遇到的枚举无法直接用trans过滤器翻译的问题,以下是几种可行的解决方法:
方案1:自定义Twig过滤器专门处理枚举
编写一个Twig扩展过滤器,自动将枚举对象转换为对应的翻译文本:
// src/Twig/EnumTransFilter.php namespace App\Twig; use Symfony\Component\Translation\TranslatorInterface; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; class EnumTransFilter extends AbstractExtension { public function __construct(private TranslatorInterface $translator) {} public function getFilters(): array { return [ new TwigFilter('enum_trans', [$this, 'translateEnum']), ]; } public function translateEnum(\BackedEnum $enum): string { // 自定义翻译键格式,可根据需求调整 $translationKey = sprintf('enum.notify_type.%s', $enum->name); return $this->translator->trans($translationKey); } }
然后在Twig模板中直接使用:
{{ supplier.notifyType|enum_trans }}
方案2:给枚举类添加翻译键获取方法
在你的NotifyType枚举中新增一个方法,返回对应的翻译键,再配合trans过滤器使用:
// src/Enum/NotifyType.php enum NotifyType: string { case EMAIL = 'email'; case SMS = 'sms'; // 返回翻译键,格式可自定义 public function getTranslationKey(): string { return sprintf('enum.notify_type.%s', $this->name); } }
Twig模板中调用方式:
{{ supplier.notifyType.getTranslationKey()|trans }}
方案3:直接利用字符串格式化结合trans过滤器
如果不想新增类或方法,可以直接在Twig中通过格式化枚举的name(或value)生成翻译键:
{{ 'enum.notify_type.%s'|format(supplier.notifyType.name)|trans }}
翻译文件配置示例
无论使用哪种方案,都需要在对应的翻译文件(如messages.zh_CN.yaml)中配置对应的翻译值:
enum: notify_type: EMAIL: '邮件通知' SMS: '短信通知'
内容的提问来源于stack exchange,提问作者Hricer
相关产品推荐
相关产品推荐

