Multilanguage in Symfony2 and Twig Multilanguage in Symfony2 and Twig symfony symfony

Multilanguage in Symfony2 and Twig


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 versionhttp://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.