Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multilanguage in Symfony2 and Twig

how to create multilanguage page in Symfony? In Symfony 1.0, Jobeet tutorial has very good description. But now on symfony.com, i haven't seen somethings related to translation of page. In symfony 1.4, echo __('text'); is used, but now in Symfony 2 TWIG is used.

like image 270
Martin Sowning Avatar asked Nov 25 '11 15:11

Martin Sowning


1 Answers

There is a documentation section on this on the Symfony2 website.

You can check it here: Translations

Basically, you have access in the routing to a special attribute named _locale that is put in your url and will be used to set the locale in the session. Note that using this scheme, the locale value is automatically set into the Session by Symfony2

http://www.host.com/en/contact // English version
http://www.host.com/fr/contact // French version

You can also specify a default _locale value in your routes so it is not mandatory to provide the locale in the url.

http://www.host.com/contact    // English version if default _locale is 'en'

Then, in twig, you use the special transformer trans and transchoice to translate messages. Your messages can be a key or an natural language message that is used as the key, usually in english.

{{ 'user.prompt.welcome' | trans }} {# Key message #}
{{ 'Welcome to our site' | trans }} {# Natural language message #}

The locale to translate the message is taken from the session, so changing the locale in the session (via the url or programmaticaly), will change the translation to another thing.

This uses the translator service under the hood.

like image 154
Matt Avatar answered Oct 16 '22 18:10

Matt