How to repeat a block of Jinja2?

2

I'm using Jinja2 as a template engine for generating a static HTML site in a Python script.

I want to repeat the contents of a block ( title ) in the layout template ( layout.html

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

This template will be extended by something like this:

{% extends "layout.html" %}
{% block title %}Titulo da pagina{% endblock %}
{% block content %}
Aqui vai o conteudo da pagina
{% endblock %}

But this does not work, resulting in an error:

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

jinja2 interprets the second {% block title %} in layout.html as a block reset.

How can I do to repeat the contents of a block in the same template, with jinja2?

    
asked by anonymous 03.01.2014 / 22:05

1 answer

2

The solution was posted in response to my question in the SO .

Just use the special variable self to access the block by name:

<title>{% block title %}{% endblock %} - {{ sitename }}</title>
<!-- ... snip ... -->
<h1>{{ self.title() }}</h1>
    
05.01.2014 / 13:37