user2467128 user2467128 - 7 months ago 89
PHP Question

How to use a Symfony Translator in my Twig template?

I've been working on translating my application, I pull the translations from my database and add them to a catalogue. Everything works within Symfony, if I echo a translation with

for example it echoes the correct value, so I assume that my translations are correct.

Now I use Twig as my template engine, which supports translations with the {% trans %} tags. Sadly the translations from the translator variable don't work within Twig and after Googling for quite a while I can't seem to find a working solution.

I've read about doing something with adding extensions using
, but I can't get that to work.

I would appreciate it if someone could point me in the right direction or maybe even provide a clearer explanation on how to achieve using the translator with the {% trans %} tags.

Thanks in advance.

Edit: Here's the code from the Controller I use to create a translator:

$this->translator = new Translator('en');
$this->translator->addLoader('array', new ArrayLoader());
$this->translator->addResource('array', $translations, 'en');

echo $this->translator->trans('TEST_TRANSLATION');

The $translations variable contains an array with the translations, when using echo it shows the given translation correctly. How can I get this translator to work in Twig when using
<p>{% trans %}TEST_TRANSLATION{% endtrans %}</p>

Edit 2: I've been trying all kinds of stuff in the last 1,5 hours, but nothing works. I have found out however that giving the translator to the array for the render function of the Twig template enables me to acces its variables, I do this as follows:

return $this->render('test/transTest.html.twig', array('translator'=>$this->translator));

If I use the above I can access the translation variables within Twig by doing:

<p>{{ translator.trans('TEST_TRANSLATION') }}</p>

<p>{{ translator.locale }}</p>
also gives me the right locale information.

I am pretty sure now that nothing is wrong with translations, but the site I'm working on uses {% trans %} for translations within Twig and I still have no idea how to get my Translator translations to work with those. Any help would be greatly appreciated.


Translation are not working in twig with the tag {% trans %} or with the filter |trans because you are not using the default translator service of Symfony but one you just instantiate.

You can load the translation from the database in a custom loader service declared in the container with the tag translation.loader so that translator service will be aware of them.

See this SO post and the (quite old) advise tutorial