简体   繁体   中英

How to set the locale on a request using symfony 3.4

I am using symfony 3.4 and I want to set the display locale for a request.

I tried as explained in the Symfony documentation with the following code

namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class EventListener
{
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $request->setLocale('en');
    }
}

but it doesn't affect the page. On the symfony status bar it still shows me de_DE as locale. I read the explanation on this stackoverflow post , but I feel like I did exactly what is described there. So what did I miss?

The custom listener must be called before LocaleListener, which initializes the locale based on the current request. To do so, set your listener priority to a higher value than LocaleListener priority (which you can obtain running the debug:event kernel.request command). check the documentation https://symfony.com/doc/3.4/translation/locale.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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