Rendering a Form in a Twig Template with Symfony2

11,388

Embedded Controller is what you need. Put your admin_bar block into separate file:

{# 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>

Create controller for this template:

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

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

And then embed controller into your original template:

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

{% block content %}
{% endblock %}
Share:
11,388
celestialorb
Author by

celestialorb

Updated on June 04, 2022

Comments

  • celestialorb
    celestialorb almost 2 years

    I have a base Twig template that has a search bar form in it at the top of the page in a Twig block. I have another block later on named "content" that my children pages fill out. Currently, my base template looks like this:

    {% 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 %}
    

    However, when trying to render a child template I need to pass in the search_form variable along with it. Is there anyway (short of writing out the HTML tags myself) I can avoid having to create this search_form variable and pass it in everytime I want to render a child view? I'm using Twig in conjunction with Symfony2.

    Thanks!