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?
Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.
All the block tag does is tell the template engine that a child template may override those placeholders in the template. In your example, the base template (header. html) has a default value for the content block, which is everything inside that block. By setting a value in home.
Use the special self
variable to access the block by name:
<title>{% block title %}{% endblock %} - {{ sitename }}</title> <!-- ... snip ... --> <h1>{{ self.title() }}</h1>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With