gremo
gremo

Reputation: 48487

Translating using variables in Symfony2 + Twig is possible?

The first output the string not translated:

{{ chart.name~'.short'|trans({}, "charts") }}

This one works (is the same text that chart.name~'.short' should output):

{{ 'charts.region.area.short'|trans({}, "charts") }}

Am i missing something? It seems it's impossible to translating dynamic text in Twig?

EDIT: working setting a variable (why?):

{% set name = chart.name ~ '.short' %}
{{ name|trans({}, "charts") }}

Upvotes: 8

Views: 12474

Answers (2)

user2394869
user2394869

Reputation: 1

when using multilanguage with symfony2 into twig you need to:

Set the Request locale, this gives the locale in which the tran twig tag will translate the word.

what I did was the following:

1- Controller part:

 $this->getRequest()->setLocale('es_AR');   //setting the locale to spanish in Argentina

 return $this->render('LoginLoginBundle:Default:welcome.html.twig');   //render a twig file

2- the twig file has a

<h2>{% trans %} hello {% endtrans %}</h2>

code with the twig tag trans, use it this way or {{ "Text"|trans }} because {% trans hello %} do not work any more

3- in the file messeges.es.yml I got

hello: Hola

This goes in order to translate the word in the

{% trans %} hello {% endtrans %}

,ore over you can change the hello word for any one you like and change it in the messeges.es.yml file, example: 1: Hola will bring Hola if the locale is set to spanish, else will bring a 1

Upvotes: 0

Czechnology
Czechnology

Reputation: 15012

Symfony/Twig is trying to translate .short and concatenate it with contents of chart.name. Use parentheses to get the expected output:

{{ (chart.name~'.short')|trans({}, "charts") }}

Upvotes: 29

Related Questions