Zagloo
Zagloo

Reputation: 1387

Symfony - Twig - Dynamic variable - How to concatenate two variables in a loop

I have to concatenate two variables in one, beside the request.locale

I explain to you :

I have an Entity named Lexicon with several field: wordFr, wordEn, definitionFr, definitionEn

I tried to do something like that for replace the Fr or En according to the request.locale but it doesn't work :

             {% set locale = '' %}

             {% if app.request.locale == "fr" %}
                 {% set locale = 'Fr' %}
             {% else %}
                 {% set locale = 'En' %}
             {% endif %}

             {% for wordList in wordsList %}
                 <tr>
                     <td>{{ wordList.word~locale }}</td>
                     <td>{{ wordList.definition~locale }}</td>
                 </tr>
             {% endfor %}

How to have {{ wordList.wordFr }} or {{ wordList.wordEn }} according to the locale (replace var locale by Fr or En) ? thanks !

In the meanwhile I did this but it's too long and repetitive...

                {% if app.request.locale == "fr" %}
                    {% for listeMots in listeMotsLexique %}
                        <tr>
                            <td>{{ wordList.wordFr }}</td>
                            <td>{{ wordList.definitionFr }}</td>
                        </tr>
                    {% endfor %}
                {% else %}
                    {% for listeMots in listeMotsLexique %}
                        <tr>
                            <td>{{ wordList.wordEn }}</td>
                            <td>{{ wordList.definitionEn }}</td>
                        </tr>
                    {% endfor %}
                {% endif %}

Upvotes: 0

Views: 1104

Answers (1)

Jamt
Jamt

Reputation: 346

What you want is to use the Twig attribute function which is documented here.

It allows you to use dynamic variable names. You would have to do something like that:

{{ attribute(wordList, 'mot'~locale) }}

You're basically saying that you want the 'mot'~locale from the wordList object

Upvotes: 5

Related Questions