3

I have verified that if I add the following line to my twig template, it outputs the desired locale:

{{ app.request.locale }}

However, the following is outputting in English:

{{ 'String'|trans }}

If I force the locale of the trans filter:

{{ 'String'|trans({}, 'messages', 'ja') }}

It outputs in the proper translation. Note that I'm setting the locale using an eventListener:

public function onKernelRequest(GetResponseEvent $event)
{
    $request = $event->getRequest();
    $locale = $request->cookies->get('_locale') ? $request->cookies->get('_locale') : $request->getPreferredLanguage($this->availableLanguages);

    $request->setLocale($locale);
}
Kai
  • 3,803
  • 1
  • 16
  • 33

2 Answers2

2

I figured out the answer through Symfony Documentation:

Setting the locale using $request->setLocale() in the controller is too late to affect the translator.

Either set the locale

  • Via a Listener (like above)
  • Via the URL (see next)
  • Or call setLocale() directly on the Translator Service.

I ended up fixing it by changing the priority of the service, like the accepted answer in this thread: Symfony 2.1 set locale

Community
  • 1
  • 1
Kai
  • 3,803
  • 1
  • 16
  • 33
2

Mabey a late reply but I was facing the same problem, after a bit of reading i found a better solution. You can use the trans function instead of the trans filter which seems to be a cleaner solution.

{% trans from "your-trans-domain" into app.user.locale %} trans.key {% endtrans %}

See symfony docs:

Docs v2.7 for translations

Vincent T
  • 3,044
  • 2
  • 9
  • 18