问题描述
我创建了一个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 / fr 或 localhost:8000 / en 时,它可以正常工作很好,显示了我的 home / index.html.twig 。
问题是当我运行 localhost:8000 / 时,它显示了默认的 Welcome to Symfony 页面,其中显示“您正在查看此页面,因为您没有配置了任何首页网址。”
sf2的this solution是否可以在sf4上使用?
有人知道如何解决吗?
我还测试了将HomeController中的路由更改为:@Route("/{_locale}",name="home",defaults={"_locale"="fr"}
但返回异常:Route pattern "/{_locale}/{_locale}" cannot reference variable name "_locale" more than once.
解决方法
我猜想路由配置错误。我不记得默认的行为,我们可以通过在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
我知道以前的配置有效,但是我不知道这是否是更优雅的方法:)
,解决方法,已添加:RedirectMatch ^/$ /fr
在我的虚拟主机中(使用apache2服务器)
纯symfony解决方案应该更好!