You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony 5是否可以实现路由的自动多语言翻译?

解决方案

完全可以实现,无需为每个语言单独定义路由注解,Symfony原生支持路由路径的多语言翻译,具体操作步骤如下:

1. 配置全局语言参数

先在config/packages/services.yaml中定义支持的语言列表参数:

parameters:
  app.supported_locales: 'en|es'

同时在config/packages/framework.yaml中配置默认语言和允许的locale:

framework:
  default_locale: en
  enabled_locales: ['en', 'es']

2. 新增路由翻译文件

在项目translations/目录下新建路由专属的翻译文件,将路径的翻译内容统一存放在这里:

  • 英文翻译translations/routes.en.yaml:
    path_profile: /profile
    
  • 西班牙文翻译translations/routes.es.yaml:
    path_profile: /perfil
    

3. 定义多语言路由

控制器中仅需要写一次路由注解即可:

#[Route(
    path: '/{_locale}/{_translated_path}',
    name: 'profile',
    requirements: [
        '_locale' => '%app.supported_locales%',
        '_translated_path' => '%path_profile%'
    ],
    methods: ['GET']
)]
public function profile()
{
    // 你的业务逻辑
}

如果使用的是Symfony 6.2及以上版本,还可以用更简洁的AsTranslatableRoute注解,直接在注解中关联翻译键即可,无需手动定义路径参数:

use Symfony\Component\Routing\Annotation\AsTranslatableRoute;

#[AsTranslatableRoute(
    path: 'path_profile', // 直接对应翻译文件中的键名
    name: 'profile',
    methods: ['GET']
)]

最终效果

  • 访问/en/profile和/es/perfil都会匹配到该路由,框架会自动设置对应locale
  • 生成路由链接时,直接调用path('profile')即可,框架会根据当前locale自动生成对应语言的URL路径
  • 后续新增支持语言时,只需要在supported_locales中新增语言编码,再新增对应语言的路由翻译文件即可,无需修改路由注解

内容的提问来源于stack exchange,提问作者Cristian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 20:06:02