首页 > 解决方案 > 可以在 Symfony 5 中自动翻译路由吗?

问题描述

我的控制器上有以下路线:

#[Route('/{_locale<en>}/profile', name: 'profile_en', methods: 'GET')]
#[Route('/{_locale<es>}/perfil', name: 'profile_es', methods: 'GET')]

可以将我所有的网址翻译(在这种情况下为配置文件)放在一个文件中并执行类似的操作吗?

#[Route('/{_locale<%app.supported_locales%>}/profile', name: 'profile', methods: 'GET')]

这应该给我所有可能的语言环境+个人资料网址已翻译

标签: phpsymfonysymfony5

解决方案


从 symfony 4.1 开始,他们有了国际化的路线(又名 Localized Routes)

快速预览:

# config/routes.yaml
about_us:
    path:
        en: /about-us
        nl: /over-ons
    controller: App\Controller\CompanyController::about

由于您已经使用_locale并且在您的情况下使用 php-attributes 它应该是:

#[Route(path: [
        'en' => '/profile',
        'es' => '/profil'
    ], name: 'profile', methods: 'GET')]

我想,这正是你要找的。但未经测试,因为我现在无法使用 php-8

PS您也可以将您的路线重命名为,profile_i18n以便每次您(或其他开发人员)使用它时,您立即知道→这是一个国际化的


推荐阅读