Reputation: 23806
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:
<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 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?
Upvotes: 34
Views: 12449
Reputation: 159885
Use the special self
variable to access the block by name:
<title>{% block title %}{% endblock %} - {{ sitename }}</title>
<!-- ... snip ... -->
<h1>{{ self.title() }}</h1>
Upvotes: 62