Twig form_theme _self自定义单个字段

时间:2014-01-29 04:21:44

标签: symfony twig

我有一个视图,我试图按http://symfony.com/doc/current/cookbook/form/form_customization.html#how-to-customize-an-individual-field覆盖单个字段的表单主题。

视图看起来像这样:

{% form_theme form _self %}

{% block _my_form_foo_widget %}
    <div class="input-append">
        {{ block('number_widget') }}
        <span class="add-on">%</span>
    </div>
{% endblock %}

<form>
    {{ form_row(form.foo) }}
    {{ form_row(form.bar) }}
</form>

foo和bar行的所有内容都是预期的,但_my_form_foo_widget块本身也包含在输出中,即:

<div class="input-append">
    <span class="add-on">%</span>
</div>

<form>
    <div>
        <label for="my_form_foo">Bar</label>
        <div class="input-append">
            <input type="text" id="my_form_foo" name="my_form[foo]">
            <span class="add-on">%</span>
        </div>
    </div>
    <div>
        <label for="my_form_bar">Foo</label>
        <input type="text" id="my_form_bar" name="my_form[bar]">
    </div>
</form>

我不能为我的生活弄清楚我做错了什么。作为一种解决方法,我只是在HTML注释中包含了块。

我在Symfony 2.4.1和Twig 1.15.0上。

1 个答案:

答案 0 :(得分:8)

您遇到twig预期的行为。

如果您没有扩展另一个模板,则会在当前模板中直接呈现新定义的块。


示例:

template_A.html.twig

  • 有一个主体(=块外的代码)=&gt;直接渲染的块

<html>
<body>
{% block content -%}
Foo
{%- endblock -%} 

Bar

{%- block more_content -%}
Foo
{%- endblock %}
</body>
</html>

=&GT;输出:FooBarFoo(正在渲染模板+正文中的所有块)


示例:

template_B.html.twig

  • 扩展模板不允许有正文
  • 只会呈现template_A.html.twig
  • 中存在的块

{% extends 'templateA.html.twig' %} 

{% block content -%}
Bar
{%- endblock %}

{% block not_in_template_a %}
Some String
{% endblock %}

=&GT;输出:BarBarFoo(但渲染Some String,因为原始模板中不存在块not_in_template_a

相关问题