0

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

并设置:

配置/包/translation.yaml

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

配置/路由/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',
        ]);
        
    }

我在翻译文件中有翻译文件,当我运行localhost:8000/frlocalhost:8000/en时,它工作正常,显示了我的home/index.html.twig

问题是当我运行localhost:8000/时,它向我显示了默认的Welcome to Symfony页面,并显示“你正在看到这个页面,因为你没有配置任何主页 URL。”

这个 sf2 的解决方案是否适用于 sf4?
有人知道如何解决吗?

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

4

2 回答 2

0

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

纯 symfony 解决方案应该更好!

于 2020-10-09T09:48:00.730 回答
0

我猜是一个糟糕的路由配置。我不记得我们可以通过在 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

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

于 2020-10-09T06:18:44.483 回答