Tag Archives: twig

Forcing the translator locale in Twig

I’ve been using Symfony2 for only a week now, but I’m already fully immersed in the SF2 world. Learning Symfony2, YAML, Twig and MongoDB all at the same time. This means I’m spending lots of time either in the official documentation, or on Google. For a test case, I’m localizing a small web application, so it’s available in 2 languages. One problem I was facing was that I needed to force certain translation tags in a specific language. Example: The link text for the French version of the current page doesn’t have to be “French”, but rather “fran├žais”, if a French person is to understand it. If you’re also using Twig, you should be familiar with the syntax to provide a translation for a text or tag:

{% trans %}Hello world!{% trans %}

To force this in the French locale (provided you have a French localization in place), you can use the “in” modifier:

{% trans in 'fr' %}Hello %name%!{% trans %}

I couldn’t find this anywhere in the Symfony2 documentation. But luckily the code itself produced the information I needed. Hopefully this saves you a search in the code.