Twig 如何获取Symfony 4项目中的所有URL以包含_语言环境
我正在尝试为symfony4项目(使用Twig)创建一个语言切换器。基本上,当点击链接时,网站的语言会发生变化 我的配置如下:Twig 如何获取Symfony 4项目中的所有URL以包含_语言环境,twig,symfony4,Twig,Symfony4,我正在尝试为symfony4项目(使用Twig)创建一个语言切换器。基本上,当点击链接时,网站的语言会发生变化 我的配置如下: config\packages\translation.yaml framework: default_locale: en translator: default_path: '%kernel.project_dir%/translations' fallbacks: - en 这是我听到的重要
config\packages\translation.yaml
framework:
default_locale: en
translator:
default_path: '%kernel.project_dir%/translations'
fallbacks:
- en
这是我听到的重要的台词
config\packages\services.yaml
:
parameters:
locale: 'en'
# This parameter defines the codes of the locales (languages) enabled in the application
app_locales: en|fr
我的控制器:
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Constraints\Json;
// Class name really should match Controller name
class ControllerBase extends AbstractController
{
/**
* @Route("/{_locale}", name="app_landing", defaults={"_locale" = "en"}, requirements={"_locale" = "en|fr"})
*/
public function index(Request $request)
{
$locale = $request->getLocale();
return $this->render('landing/index.html.twig');
}
}
经过一段时间的实验,我找到了答案 我试着用两种不同的方式做同样的事情。在我的例子中,最好只使用模板文件中的代码,并省略控制器中的{u locale}参数 像那样一切都很好