Translating using variables in Symfony2 + Twig is possible?

独自空忆成欢 提交于 2019-12-30 06:32:01

问题


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") }}

回答1:


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") }}



回答2:


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

来源:https://stackoverflow.com/questions/7730355/translating-using-variables-in-symfony2-twig-is-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!