rfc1484 rfc1484 - 7 months ago 21
PHP Question

Translations not working in Symfony2

I have a file with french translations located in

FooBundle/Resources/translations/messages.fr.xlf


Example:

<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="en" datatype="plaintext" original="file.ext">
<body>
<trans-unit id="1">
<source>Foo</source>
<target>Bar</target>
</trans-unit>
</body>
</file>
</xliff>


But I can't seem to make any translation work, neither in the controller:

// FooBundle/Controller/DefaultController.php
/**
* @Route("/")
* @Template()
*/
public function indexAction(Request $request)
{
$request->setLocale("fr");
$translatedMessage = $this->get('translator')->trans('Foo');

echo $translatedMessage;

return array();
}


Or the twig template:

// FooBundle/Resources/views/Default/index.html.twig
{{ 'Foo'|trans }} or {% trans %}Foo{% endtrans %}


It always shows
Foo
(the original string).

As my default locale I use english ('en'). My locale config from
config.yml
:

framework:
translator: { fallback: "%locale%" }
default_locale: "%locale%"
...


I've tried to clean up the cache but it didn't make any difference.

If I try to debug the translations, it shows that they are being used:

$ php app/console debug:translation fr FooBundle

+----------+---------------+----------------------+
| State(s) | Id | Message Preview (fr) |
+----------+---------------+----------------------+
| | Foo | Bar |
+----------+---------------+----------------------+


Any idea what is going wrong here?

Answer

It seems that the problem was another bundle I have installed (LuneticsLocaleBundle).

Somehow it must override the $request->setLocale("fr"); I do in the controller so it turns out I was using en_US as locale. That was the reason why it wasn't showing the translations.