lampshade
lampshade

Reputation: 2786

Symfony 4 won't translate and always shows the English default

I'm running Symfony 4 and I installed the translation system using

composer require symfony/translation

I've create two files in /translations:

Using php bin/console debug:translation es I also get the correct result:

----------- ---------- ------ ---------------------- ------------------------------- 
 State       Domain     Id     Message Preview (es)   Fallback Message Preview (en)  
----------- ---------- ------ ---------------------- ------------------------------- 
             messages   test   Value ES               Value EN                       
----------- ---------- ------ ---------------------- ------------------------------- 

The entries look like this:

<trans-unit id="test">
    <source>test</source>
    <target>Value EN</target>
</trans-unit>

and this:

<trans-unit id="test">
    <source>test</source>
    <target>Value ES</target>
</trans-unit>

In my controller I set the locale, which seems to work fine and is also represented in the Twig templates:

public function index(Request $request, TranslatorInterface $translator)
{
    $request->setLocale('es');
    // prints 'es'
    print $request->getLocale();
    return $this->render();
}

And in Twig:

{# prints 'es' #}
{{ app.request.locale }}

However, when I now run:

print $translator->trans('test');

or:

{{ 'test'|trans }}

I always get Value EN, which seems not correct as it should be Value ES.


I'm running Symfony 4.0 and cleared the cache multiple times - even deleted the whole folder.

The translations.yml looks like this:

framework:
    default_locale: '%locale%'
    translator:
        paths:
            - '%kernel.project_dir%/translations'
        fallbacks:
            - '%locale%'

And the services.ymllooks like this:

parameters:
    locale: 'en'
    locales: en|de|es

What am I missing here?

Upvotes: 1

Views: 2434

Answers (1)

Jack Skeletron
Jack Skeletron

Reputation: 1501

From official documentation

To set the user's locale, you may want to create a custom event listener so that it's set before any other parts of the system (i.e. the translator) need it:

And then (this is the part that explains your code behaviour)

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), the URL (see next) or call setLocale() directly on the translator service.

Upvotes: 4

Related Questions