Translate the value of twig variable

1.6k views Asked by At

Is it possible to translate the value of twig variables in a template with the 'trans' tag?

Say for instance I am passing a product to my template. This product has a definition with a trans tag e.g {{ product.definition|trans }}. This definition could either be in EN or DE or some other language. How could I translate the definition.

2

There are 2 answers

0
ExcellentAverage On

If {{ product.definition }} equals 'cellphone' the following should work.

message.language.yml:

'cellphone': This will work!

However if you want to map it with the 'product' key in your message file like this:

product:
    'cellphone': This also works

add the key to the twig template like so:

{{('product.'~product.definition)|trans }}
0
xurshid29 On

What are you trying to do is not a good way, It would look like this:

messages.en.yml

product:
    definition:
        some_value1: Some value 1
        some_value2: Some value 2

and in template, you would do something like this:

{% set definition_value = product.definition %}
{% set trans_definition = 'product.definition.' ~ definition_value %}
{{ trans_definition|trans }}

it'll work, if it finds the key. What if it cant find it?

That's why you should use DoctrineBehaviors from KnpLabs, which handles all the dynamic translations for you..