How to handle Translation in twig file using variables?
Asked Answered
C

1

46

I have a twig file and a yml, in which I define the variables for translation

e.g.:

YML File -
variable.for.translation: Disponible, para tí

Content of Twig File -

<h2>"Hola, Follow {{ variableName }} en Twitter</h2>  

I wanted to make a variable for

Hola, Follow {{ variableName }} en Twitter

in translation file (i.e my yml file).
Currently i am doing it like this :
In YML -

follow.us.twitter: Hola, Follow 

follow.us.twitter1: en Twitter 

In Twig -

<h2>{{ "follow.us.twitter"|trans([], "workend") }} {{ variableName }} {{ "follow.us.twitter1"|trans([], "workend") }}</h2> 

Its working fine, but the problem is that i now have 3 variables in a twig which are too much :

 1. follow.us.twitter
 2. follow.us.twitter1
 3. {{ variableName }}

I tried to do it with a single variable, like so:

follow.us.in.twitter : Hola, Follow {{ variableName }} en Twitter 
and  
<h2>{{ "follow.us.in.twitter"|trans([], "workend") }}</h2>

but it didn't work. The problem is the variable i.e {{ variableName }} I am using.

Is there any way to do handle a predefined variable and define it in translation file?

Connatural answered 4/1, 2012 at 12:8 Comment(0)
G
93

You were going on right track, what you missed is just to pass someVariable as a parameter to trans() in your Twig file as:

<h2>{{ "follow.us.in.twitter"|trans({'%someVariable%': someVariable}, "workend") }}</h2>

Now your message in Yml file should be as:

follow.us.in.twitter: Hola, Follow %someVariable% en Twitter

This should work. For more details and clarity you can refer the following: Symfony Book

Good Luck.

Grimace answered 5/1, 2012 at 10:23 Comment(2)
If I pass many arguments to twig, can't Twig just use the whole array without defining them to trans? So if I have: {{ reminder.Email|trans({'%firstName%' : firstName, '%lastName%' : lastName, '%siteUrl%' : siteUrl}) }} why can't just map a whole array, that will be used to replace %var% with var?Mielke
Will be better if this is replaced by this.. {'%variableName%': variableName} ===> {'%variableName%': variableValue}Maulmain

© 2022 - 2024 — McMap. All rights reserved.