Xavier
Xavier

Reputation: 4017

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:

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

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

I tried both..

I register the Listener in the service.yml:

 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...

The listener seems to works, i can get the Locale in my controller with a $request->getLocale()(or session).

But Twig is still in the default language I defined in the config.yml:

parameters:
    locale: fr

I'm pretty lost now, any tips ?

Upvotes: 3

Views: 1679

Answers (2)

NgocDB
NgocDB

Reputation: 131

You have to set the locale for the translator to get the right translation in templates.

E.g in controller:

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

Upvotes: 0

Xavier
Xavier

Reputation: 4017

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:

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...

Upvotes: 1

Related Questions