如何在 Symfony2 表单中使用 TWIG bootstrap 模板块

How to use TWIG bootstrap template block in a Symfony2 form

我不明白如何使用 bootstrap_3_horizontal_layout.html.twig 中定义的块来自定义我的表单。

到目前为止,我已经这样做了,而且工作正常。

{% form_theme form 'bootstrap_3_horizontal_layout.html.twig' %}
<div class="well">
    {{ form_start(form) }}

    {{ form_errors(form) }}

    {{ form_row(form.title, {'label': 'Titre'}) }}

    {{ form_row(form.content, {'label': "Content"}) }}

 ...

    {{ form_rest(form) }}
    {{ form_end(form) }}
</div>

但是如果我尝试使用。或 bootstrap_3_horizontal_layout 中定义的任何其他块,如

{{ textarea_widget(form.content, {'label': "Content"}) }}

没用。

您在第一个示例中调用的函数(form_startform_errors 等)是在 [=28= 的 Twig 扩展 (documentation) 中定义的函数]使用定义的主题来生成输出。所以在 bootstrap_3_horizontal_layout.html.twig 中定义的块被那些函数调用(它们是 Symfony 表单视图组件的扩展),你不能自己直接 "call" 这些块。

如果您要自定义表单的输出,最简单的方法是创建您自己的从基本主题扩展而来的表单主题:

{% extends 'bootstrap_3_horizontal_layout.html.twig' %}
{% block textarea_widget %}
    {# your code #}
{% endblock %}

这在Symfony cookbook entry中有描述。

如果您尝试直接调用小部件,最好更改传递给呈现器的表单字段的类型。 form documentation. The type you choose defines which block will be rendered from your theme - so in your case if you change the field type to textarea, the textarea_widget (well, textarea_row first) will be rendered. If you need an overview of this, the form fragment naming 文档中提供了不同的可用类型,应该对您有所帮助。

感谢 John Noel,我找到了答案。 总结一下是否有人想做同样的事情。

在 Symfony2 表单中使用 bootstrap3 预定义布局

1 - 声明要使用的表单主题。

在你的树枝模板中

{% form_theme form 'bootstrap_3_horizontal_layout.html.twig' %}

或在 /app/config/config.yml

中全局获取所有表单
# Twig Configuration
twig:
    form:
        #resources: ['bootstrap_3_layout.html.twig']
        resources: ['bootstrap_3_horizontal_layout.html.twig']

2 - 使用 Symfony Twig Extensions 显示您的表单

  • 形式
  • form_start
  • form_end
  • form_enctype
  • form_widget
  • form_errors
  • form_label
  • form_row
  • form_rest

3 - 您必须在表单生成器中使用正确的 Form Type(这是我遗漏的部分)。

例如:使用 Bootstrap 3 小部件钱。

在你的form.html.twig

{% form_theme form 'bootstrap_3_horizontal_layout.html.twig' %}

  {{ form_start(form) }}

...

    {{ form_row(form.price, {'label': "Price"}) }}

...

    {{ form_end(form) }}

在您的 FormType 中

$builder->add('price', 'money');

我希望这可以帮助别人,因为这是我希望找到的! 再次感谢 John Noel