How to repeat a block in a jinja2 template?


I’m using Jinja2 as the template engine to a static HTML site generated through a Python script.

I want to repeat the content of a block in the layout template, which goes something like this:

    <title>{% block title %}{% endblock %} - {{ sitename }}</title>
    <h1>{% block title %}{% endblock %}</h1>
    <div id="content">
        {% block content %}{% endblock %}

This template will be extended in a page template, that looks like this:

{% extends "layout.html" %}
{% block title %}Page title{% endblock %}
{% block content %}
Here goes the content
{% endblock %}

However, this doesn’t work as I expected, resulting in an error:

jinja2.exceptions.TemplateAssertionError: block 'title' defined twice

Jinja interprets the second {% block title %} in layout.html as a block redefinition.

How can I repeat the content of a block in the same template using jinja2?

Asked By: Elias Dorneles



Use the special self variable to access the block by name:

<title>{% block title %}{% endblock %} - {{ sitename }}</title>
<!-- ... snip ... -->
<h1>{{ self.title() }}</h1>
Answered By: Sean Vieira
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.