2

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!

1 Answer 1

11

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 %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.