Reputation: 2434
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.)
Upvotes: 5
Views: 2287
Reputation: 11197
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:
Upvotes: 4
Reputation: 323
The simpler way would be to add a header
and footer
block to the parent template, turning this one into:
{% block header %}
<div class="wrapper">
{% endblock %}
{% block footer %}
</div>
{% endblock %}
and let the content block as-is. Jinja doesn't care if your HTML is well-formed. In fact, it isn't HTML-specific, so you can do things like this (in this case, the HTML will turn out fine though).
Upvotes: 0
Reputation: 27102
You need to give your blocks unique names. Your problem is obviously a result of the double-use of the content
block.
Upvotes: 0