我有一个表单模板,其中有几个类似表单字段的重复 block 。其使用方法如下:
{# form_template.html.twig #}
{{ include ('company-select.html.twig', {field: 'companiesInclude'})
{{ include ('company-select.html.twig', {field: 'companiesExclude'})
{{ include ('company-select.html.twig', {field: 'companiesLinked'})
现在我有一个公司选择模板,如下所示:
{# company-select.html.twig (simplified, the actual template is much more complex) #}
<div class="form form-field selector" id="{{ field }}">
{{ form_label(form.field) }}
{{ form_widget(form.field) }}
</div>
事实上,模板失败了,因为“field”不是 FormView 类的属性。
如何使模板将 twig 变量作为实际字段名称插入到 form_xxx 函数调用中?
最佳答案
twig 中的对象或数组元素的属性可以通过点符号 (.
) 或通过方括号 ([]
) 访问。
如果您的属性恰好是 twig 变量,则需要使用后面的形式。
所以在你的情况下:
form_label(表单[字段])
form_widget(表单[字段])
您在 company-select.html.twig 中的代码最终为:
<div class="form form-field selector" id="{{ field }}">
{{ form_label(form[field]) }}
{{ form_widget(form[field]) }}
</div>
在一个非常简化的示例中,这是可测试的 here .
请注意,在更复杂的风格中,您还可以使用 attribute
function
.
,[]
: Gets an attribute of a variable.
来源:https://twig.symfony.com/doc/3.x/templates.html#other-operators
同样值得一读:https://twig.symfony.com/doc/3.x/templates.html#variables
关于php - 如何使用 Twig 变量作为表单字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64579463/