首页 > 解决方案 > How to concatenate a field in a form with a var in Twig?

问题描述

I'm trying to work with a loop in a Controller (in Symfony4) to create a form, with different lines

for ($i=1 ; $i<=$nblig ; $i++)
                {
                $formBuilder  ->add('date'.$i, DateType::class)
                              -> (...)
                }

The form works fine (I can dump it). I need a similar loop, when I try to render that form with Twig :

{% for i in 1..nblig %}
  {{ form_widget(form.date ~ i)) }}{% endfor %} 

And I don't know how to concatenate the field name date, with the var i.

Thanks for your help

标签: twigconcatenationsymfony4

解决方案


您现在正在组合form.datewith的值i,您想要什么,您可以使用数组表示法或使用attributefor

{{ form_widget(form['date' ~ i]) }}

{{ form_widget(attribute(form, 'date'~i)) }}

推荐阅读