如何使用树枝变量作为表单字段名称
How can I use a twig variable as a form field name
我有一个表单模板,其中有几个类似表单域的重复块。用法如下:
{# 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'})
现在我有一个公司select模板,如下所示:
{# 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 class 的 属性。
如何让模板将 twig 变量作为实际字段名称插入到 form_xxx 函数调用中?
Twig 中对象或数组元素的 属性 可以通过点符号 (.
) 或方括号一 ([]
) 访问。
如果你的 属性 恰好是一个 twig 变量,你将需要使用后面的形式。
所以在你的情况下:
form_label(form[field])
form_widget(form[field])
您在 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
我有一个表单模板,其中有几个类似表单域的重复块。用法如下:
{# 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'})
现在我有一个公司select模板,如下所示:
{# 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 class 的 属性。
如何让模板将 twig 变量作为实际字段名称插入到 form_xxx 函数调用中?
Twig 中对象或数组元素的 属性 可以通过点符号 (.
) 或方括号一 ([]
) 访问。
如果你的 属性 恰好是一个 twig 变量,你将需要使用后面的形式。
所以在你的情况下:
form_label(form[field])
form_widget(form[field])
您在 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