Search code examples
flaskjinja2

Wrapping blocks in Jinja 2


I have two Jinja 2 templates where the second extends the first one:

<h1>Some title</h1>
{% block content %}
{% endblock %}

and

{% block content %}
  content
{% endblock %}

Now I want to be able to insert a variable number of "wrappers" between those two templates where the second one extends the wrapper (which extends the next wrapper)* which extends the first template. A wrapper could look like this:

{% block content %}
  <div class="wrapper">
    {% block content %}
    {% endblock %}
  </div>
{% endblock %}

I would expect this to result in the following rendered HTML:

<h1>Some title</h1>
<div class="wrapper">
  content
</div>

Unfortunately, the wrapper template from above is not valid in Jinja 2, because blocks simply don't work like this. So is there any way to do what I want to do in Jinja 2? If not: Are there any other template engines that are capable of it?

(Note that renaming the inner block won't do, because I need to be able to add a variable number of wrappers.)


Solution

  • Use:

    {% block content %}
      <div class="wrapper">
        {{ super() }}
      </div>
    {% endblock %}
    

    From the Jinja 2 documentation:

    It’s possible to render the contents of the parent block by calling super. This gives back the results of the parent block: