Symfony - Twig - 动态变量 - 如何在循环中连接两个变量
Symfony - Twig - Dynamic variable - How to concatenate two variables in a loop
除了 request.locale
之外,我还必须将两个变量合二为一
我给你解释一下:
我有一个名为 Lexicon
的实体,其中包含多个字段:
wordFr
、wordEn
、definitionFr
、definitionEn
我尝试做类似的事情来根据 request.locale
替换 Fr
或 En
但它不起作用:
{% 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 %}
如何根据语言环境设置 {{ wordList.wordFr }}
或 {{ wordList.wordEn }}
(将 var locale
替换为 Fr
或 En
)?谢谢!
同时我做了这个,但是它太长而且重复...
{% 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 %}
您想要的是使用记录在案的 Twig attribute
函数 here。
它允许您使用动态变量名。
你将不得不做这样的事情:
{{ attribute(wordList, 'mot'~locale) }}
你基本上是说你想要 wordList
对象的 'mot'~locale
除了 request.locale
我给你解释一下:
我有一个名为 Lexicon
的实体,其中包含多个字段:
wordFr
、wordEn
、definitionFr
、definitionEn
我尝试做类似的事情来根据 request.locale
替换 Fr
或 En
但它不起作用:
{% 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 %}
如何根据语言环境设置 {{ wordList.wordFr }}
或 {{ wordList.wordEn }}
(将 var locale
替换为 Fr
或 En
)?谢谢!
同时我做了这个,但是它太长而且重复...
{% 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 %}
您想要的是使用记录在案的 Twig attribute
函数 here。
它允许您使用动态变量名。 你将不得不做这样的事情:
{{ attribute(wordList, 'mot'~locale) }}
你基本上是说你想要 wordList
对象的 'mot'~locale