【问题标题】:Symfony 4 with translations, no route to / without _locale带有翻译的 Symfony 4,没有到/没有 _locale 的路径
【发布时间】:2021-01-23 14:28:39
【问题描述】:

我创建了一个包含英语和法语翻译的 Symfony 4.4.8 项目,所以我按照以下步骤操作:
https://symfony.com/doc/current/translation.html

并设置:

config/packages/translation.yaml

framework:
    default_locale: 'fr'
    translator:
        default_path: '%kernel.project_dir%/translations'
        fallbacks: ['en', 'fr']

config/routes/annotations.yaml

controllers:
    resource: ../../src/Controller/
    type: annotation
    prefix: /{_locale}/
    requirements:
        _locale: fr|en

和一个 src/Controller/HomeController.php

class HomeController extends AbstractController
{
    private $session;
    
    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

    /**
     * @Route("/", name="home")
     */
    public function index() {
        return $this->render('home/index.html.twig', [
            'controller_name' => 'HomeController',
        ]);
        
    }

我在 translations 文件夹中有翻译文件,当我运行 localhost:8000/frlocalhost:8000/en 时,它可以工作好的,我的 home/index.html.twig 显示出来了。

问题是当我运行 localhost:8000/ 时,它会显示默认的 Welcome to Symfony 页面,并显示“您正在查看此页面,因为您还没有配置任何主页 URL。”

sf2 的 this solution 是否适用于 sf4?
有人知道怎么解决吗?

我还测试了将 HomeController 中的路由更改为:
@Route("/{_locale}", name="home", defaults={"_locale"="fr"}
但它返回异常:
Route pattern "/{_locale}/{_locale}" cannot reference variable name "_locale" more than once.

【问题讨论】:

    标签: symfony translation symfony-4.4


    【解决方案1】:

    解决方法,已添加:
    RedirectMatch ^/$ /fr
    在我的虚拟主机中(使用 apache2 服务器)

    纯 symfony 解决方案应该更好!

    【讨论】:

      【解决方案2】:

      我猜是一个糟糕的路由配置。我不记得我们可以通过在 URL 中添加语言环境代码来设置语言环境的默认行为,所以我猜这是您添加的内容;)

      Symfony 以与您声明路由相同的顺序解析路由。因此,一种解决方案是导入 2 次相同的路线,但带有前缀:

      # config/route.yaml
      app_front:
          type: annotation
          resource: '../src/Controller/*.php'
          prefix: /
          options:
              expose: true
      
      app_localized_front:
          type: annotation
          resource: '../src/Controller/*.php'
          name_prefix: localized_
          prefix: /{locale}
          options:
              expose: true
      

      我知道以前的配置有效,但我不知道这是否是更优雅的方式:)

      【讨论】:

      • 感谢您的回答,有了它, localhost:8000 显示了正确的页面......但是如果我切换到另一个页面,它就可以工作,总是没有 _locale 并且如果我点击在我的 en 菜单上切换英文,它保持在法文,只需在 url 末尾添加 ?_locale=en
      • 因此您可能必须删除app_localized_front 并添加一个事件侦听器,该侦听器从请求中查看_locale 查询并切换区域设置;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      相关资源
      最近更新 更多