Symfony2: Translations
To get the Translator you must use the dependecy injector inside the controller, basically you do this:
$this->get('translator')
You must have it enabled on the config:
framework:
translator: { fallback: en }
Now you put all your translations dictionaries on the path:
- YourApp/YourBundle/Resources/translations
- Or… if you want to override definitions from other bundles, you put them on app/Resources/translations
<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>symfony.rocks</source>
<target><![CDATA[ <strong>Symfony2</strong> esta bueno. ]]></target>
</trans-unit>
</body>
</file>
</xliff>
And on the controller you call:
$t = $this->get('translator')->trans('symfony.rocks') ;
return new Response($t);
You will get the message according to the current Locale language (in this case “es”)
Another cool feature from Symfony is the possibility to set the language in the URL of each page and automaticaly set the correct Locale on the session, to do that you use the _locale feature in the routes:
/**
* @extra:Route("/{_locale}/YourRoute", name="_testing", requirements={"_locale"="en|fr|es"})
*/
In the above example, depending on the value of _locale symfony will automatically set the correct language, so you dont have to use setLocale on the Translator!
Read more from the official documentation.
Mohammad Ali Akbari 3:29 PM on 4 November 2012 Permalink |
Can you have a look on my question about i18n in Symfony2?
http://stackoverflow.com/questions/13221364/specify-active-loaders-for-translation-component-in-symfony2