简体   繁体   English

Twig不在Symfony 3中设置语言环境

[英]Twig do not set the locale in Symfony 3

I created a EventListener to set the locale based on the user preferences, i set the langage like this in my listener: 我创建了一个EventListener来根据用户首选项设置语言环境,我在我的监听器中设置了这样的语言:

$request->setLocale($user->getLanguage());

$request->getSession()->set('_locale',$user->getLanguage());

I tried both.. 我试过两个..

I register the Listener in the service.yml : 我在service.yml注册了Listener:

 app.event_listener.locale:
        class: 'AppBundle\EventListener\LocaleListener'
        arguments:
            - '@security.token_storage'
        tags:
            - {name: 'kernel.event_listener', event: 'kernel.request', method: 'onKernelRequest'}

I also tried to add a priority: 17 to the service but it does not change anything... 我还试图为服务添加一个priority: 17 ,但它不会改变任何东西......

The listener seems to works, i can get the Locale in my controller with a $request->getLocale() (or session). 监听器似乎工作,我可以使用$request->getLocale() (或会话)在我的控制器中获取Locale。

But Twig is still in the default language I defined in the config.yml : 但是Twig仍然是我在config.yml定义的默认语言:

parameters:
    locale: fr

I'm pretty lost now, any tips ? 我现在很迷茫,有什么提示吗?

I tried a lot of stuff (change the priority, check if the locale is passed to the front etc...) Finally i forced the translator in my EventListener: 我尝试了很多东西(更改优先级,检查语言环境是否传递到前端等等)最后我强制我的EventListener中的翻译器:

public function onKernelRequest(GetResponseEvent $event)
{
    $request = $event->getRequest();

    if ($this->tokenStorage->getToken()) {
        $user = $this->tokenStorage->getToken()->getUser();
        if ($user && $user instanceof User) {
            $request->setLocale($user->getLanguage());
        } elseif ($request->query->has('locale')) {
            $request->setLocale($request->query->get('locale'));
        } else {
            $request->setLocale($request->getPreferredLanguage());
        }
    }
    $this->translator->setLocale($request->getLocale());
}

I don't understand why, this should be done in the Symfony translator, but it works... 我不明白为什么,这应该在Symfony翻译器中完成,但它有效......

You have to set the locale for the translator to get the right translation in templates. 您必须为翻译器设置语言环境才能在模板中获得正确的翻译。

Eg in controller: 例如在控制器中:

$this->get('translator')->setLocale($user->getLanguage());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM