Search code examples
phpsymfonytwiglocaletranslation

How to pass Symfony translated sentences to twig?


I am using Twig, twig-bridge, symfony/form and symfony/translator v4. Not Symfony framework. I am confused about translator. In {root}/translations/messages.fr.php I wrote:

// translations/messages.fr.php
return [
    'Symfony is great' => "J'aime Symfony",
];

In main script in {root} I wrote:

setlocale(LC_ALL, 'fr_FR');
$translator = new Translator('fr');
$translated = $translator->trans('Symfony is great');
var_dump($translated); // Not translated!

and in Twig template I wrote:

<h1>{% trans %}Symfony is great{% endtrans %}</h1>

But this is not translated. I still get the english version. What mistake I did? Should I move {root}/translations/messages.fr.php to somewhere else as this is standalone and not symfony framework?


Solution

  • If you're using Symfony Translator without the framework, you need to manually configure paths to translation files, otherwise Translator won't be able to find them and any translation attempts will fall back to the original string.

    I never did that myself, but according to the documentation, this should work for you:

    $translator->addLoader('php', new PhpFileLoader());
    $translator->addResource('php', 'path/to/messages.fr.php', 'fr_FR');