php - 如何使用 Twig 变量作为表单字段名称

标签 php forms symfony twig

我有一个表单模板,其中有几个类似表单字段的重复 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/

相关文章:

php - 使用 Ajax 更新的最佳方法

php - Imagick 注释图像 : how to set text position from the top left

php - 无法在 MySQL、PHP、AngularJS 中插入多行

php - 这段代码中定义的表单的 `submit()` 函数在哪里?

javascript - 如何将php代码输入的常量值转换为html标签形式

javascript - document.forms[i] 代码在页面中有效,但在 Greasemonkey 中出现 "undefined"错误

php - Symfony2、Doctrine2 和 PostgreSQL : error "Undefined variable: className"

doctrine-orm - Symfony3 - 添加记录 Doctrine 查询的记录器

symfony - 更新 Symfony2 上的composer.phar

php - 简单 'SELECT field FROM table_name where TO = "$to"' 返回 MySQL 错误 1064