I have a Sf2 application with a twig template extending a layout. Inside the template i want to fill a block by using twig's render tag. Unfortunately the render tag causes two sub requests instead of the expected single one. But if i place the render tag outside of the block, everything works just fine*.
*of course except that the result is rendered simply at the top of the page instead inside a block, but it's only one additional sub request.
What may cause that two sub requests are made if - and only if - the render tag is placed within a block?
In the layout there's a block for an additional navigational menu (topmenu):
layout.twig.html
<div class="row" id="secondary-nav">
<div class="span12">
{% block topmenu %}{% endblock %}
</div>
</div>
And this is my view, it uses a {% render ... %} tag to fill the topmenu block by issuing a sub request to the "Navigation" controller:
index.html.twig
{% extends "FooBundle::layout.html.twig" %}
{% block topmenu %}
{% render "FooBundle:Navigation:index" with { 'active': 'feedback' } %}
{% endblock %}
So far, so good, but doing it this way the sub request is issued twice for some unknown reason. It's not displayed twice, but i see the SQL query count increased and the symfony2 profiler shows two identical sub requests too.
If i place the {% render ... %} tag outside of any block like this, it is causing only one single sub request:
index.html.twig
{% extends "FooBundle::layout.html.twig" %}
{% render "FooBundle:Navigation:index" with { 'active': 'feedback' } %}
{% block topmenu %}
{% endblock %}
NARF! Finally, after spending X hours on this issue, i found out that i had a check in my layout.html.twig, to see if the topmenu block has any contents:
{% if block('topmenu') %} ... {% endif %}
...
{% block topmenu %}{% endblock %}
This led to the second, unwanted sub request.
Fix
To still have the ability to check for the content but not requesting twice, i'm loading the block into a variable first and then outputting the variable instead of using {% block topmenu ...%}:
{% set topmenu = block('topmenu') %}
{% if topmenu %} ... {% endif %}
{{ topmenu | raw }}
Luckily i do not need to extend the block really, it's just a placeholder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With