使用Symfony2在Twig模板中呈现表单

时间:2012-02-21 20:14:58

标签: forms templates view symfony twig

我有一个基本的Twig模板,在Twig块的页面顶部有一个搜索栏表单。我后来在另一个块上命名为“内容”,我的子页面填写完整。目前,我的基本模板如下所示:

{% block admin_bar %}
    <div id="search">
        <form action="{{ path('search') }}" method="post" {{ form_enctype(search_form) }}>
            {{ form_widget(search_form.term) }}
            {{ form_widget(search_form.type) }}
            {{ form_widget(search_form.pool) }}
            {{ form_widget(search_form._token) }}
            <input type="submit" value="Search" />
        </form>
    </div>
{% endblock %}

{% block content %}
{% endblock %}

但是,在尝试渲染子模板时,我需要传递search_form变量。无论如何(没有自己写出HTML标签)我可以避免创建这个search_form变量并在每次我想渲染子视图时传递它?我正在将Twig与Symfony2结合使用。

谢谢!

1 个答案:

答案 0 :(得分:11)

Embedded Controller就是您所需要的。将您的admin_bar块放入单独的文件中:

{# src/Acme/AcmeBundle/Resources/views/Search/index.html.twig #}
<div id="search">
    <form action="{{ path('search') }}" method="post" {{ form_enctype(search_form) }}>
        {{ form_widget(search_form.term) }}
        {{ form_widget(search_form.type) }}
        {{ form_widget(search_form.pool) }}
        {{ form_widget(search_form._token) }}
        <input type="submit" value="Search" />
    </form>
</div>

为此模板创建控制器:

class SearchController extends Controller
{
    public function indexAction()
    {
        // build the search_form

        return $this->render('AcmeAcmeBundle:Search:index.html.twig', array('search_form' => $searchForm));
    }
}

然后将控制器嵌入到原始模板中:

{% block admin_bar %}
    {% render "AcmeAcmeBundle:search:index" %}
{% endblock %}

{% block content %}
{% endblock %}