简体   繁体   English

如何在循环中连接两个Twig变量

[英]How to concatenate two Twig variables in a loop

I'm trying to create dynamically variable name so the result to be as the one below 我正在尝试创建动态变量名,因此结果如下

{{ form_label(form.user_1) }}
 {{ form_label(form.user_2) }}
 {{ form_label(form.user_3) }}
 {{ form_label(form.user_4) }}

Here's what I tried so far 到目前为止,这是我尝试过的

{%  for user in users %}
      {{ form_label(form.user~'_'~loop.index) }}
 {% endfor %}

but get 但是得到

Argument 1 passed to Symfony\\Component\\Form\\FormRenderer::searchAndRenderBlock() must be an instance of Symfony\\Component\\Form\\FormView, string given 传递给Symfony \\ Component \\ Form \\ FormRenderer :: searchAndRenderBlock()的参数1必须是Symfony \\ Component \\ Form \\ FormView的实例,给定字符串

What I'm doing wrong? 我做错了什么?

I think that you have to use the attribute() function . 我认为您必须使用attribute()函数

If this doesn't work with the concatenation in the method parameter, try to concatenate it first in a variable like this : 如果此方法不适用于方法参数中的串联,请尝试首先在这样的变量中将其串联:

{% set userIndex = 'user_' ~ loop.index %}

And then you should try this : 然后您应该尝试以下方法:

{{ form_label(attribute(form, userIndex)) }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM