Reputation: 3823
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);
}
Upvotes: 3
Views: 2554
Reputation: 3262
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:
Upvotes: 2
Reputation: 3823
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
Upvotes: 2