Bananaapple
Bananaapple

Reputation: 3114

Twig outputs Symfony form elements before I call form_row() due to use of parent() and block structure

I have two twig files - index and layout. I am trying to output a form in index.

Because of the way the templating for this site is structured I am forced to wrap the form around the very outside of the layout like demonstrated below.

This is template file:

{# layout.html.twig: #}
{% block main %}
    <!-- 
        there is actually a lot more going on here 
        and simply moving it into index would lead 
        to a lot of duplication in the html structure
    -->
    <main> 
        {% block mainContent %}
        {% endblock %}
    </main>
{% endblock %}

And this is the file implementing the template:

{# index.html.twig: #}
{% extends 'layout.html.twig' %}

{% block main %}
    {{ form(form) }}
        {{ parent() }}  
    {{ form_end(form) }}
{% endblock %}

{% block mainContent %}
    {{ form_row(form.my_field) }}
{% endblock %}

index overwrites the main block, adds the form then calls in the main parent content into the form. The parent content contains a block called mainContent into which I then actually add the form elements.

Only problem is that Symfony/Twig have other ideas and actually output all my rows before blockMain so my calls to form_row in there are simply ignored as the corresponding elements are already echoed.

How can I stop that and output my form inside blockMain but wrap it around block main?

Apologies should this be a duplicate - I am struggling to find appropriate keywords for this. While I can see what's going on (sort of), I don't actually know what the behaviour is called.

Upvotes: 0

Views: 112

Answers (1)

Bananaapple
Bananaapple

Reputation: 3114

Turns out this is a lot less complicated than I thought - I simply mixed up form() and form_start().

Everything works as it should as soon as I add in form_start() in place of form().

Upvotes: 0

Related Questions