Search code examples
symfonybrowsertranslationtranslate

Symfony 4 translation


I've been trying to work with this: https://symfony.com/doc/current/translation.html

But seems like no one have any problems with the translations, I must get it totally wrong.

My locale is set to 'fr' in 'services.yaml'

I have my message.en.xlf and message.fr.xlf

Here is my .fr:

<?xml version="1.0"?> 
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="en" target-language="fr" datatype="plaintext" original="file.ext">
        <body>
            <trans-unit id="homepage_presta">
                <source>homepage.presta</source>
                <target>Les prestations</target>
            </trans-unit>
        </body>
    </file>
 </xliff>

Been trying in controller (getting "missing translation key" warning):

var_dump($translator->trans("homepage_presta"));

or in twig:

{{ 'homepage.presta'|trans }}  

But nothing is working.. In the end I would like to translate to the right language depending on the browser language, then to some lang if selected in the navbar (like in a cookie ?).


Solution

  • /**
     * @Route("/test/translation")
     */
    public function translationAction(TranslatorInterface $translator)
    {
        dump($translator->trans("homepage.presta"));
    
        return new Response('<html><body>testaroni</body></html>');
    }
    

    works for me... a few things...

    1. the default translation domain is messages not message so your file should be translations/messages.fr.xlf

    2. I'm not used to xlf but it seems you have to use <source>homepage.presta</source> for your translation not the id homepage_presta

    3. Don't forget to clear your cache every time you create a new translation file php bin/console cache:clear