Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat a block in a jinja2 template?

Tags:

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?

like image 242
Elias Dorneles Avatar asked Jan 05 '14 02:01

Elias Dorneles


People also ask

How do you make a loop in 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.

What is block content in Jinja?

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.


1 Answers

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

<title>{% block title %}{% endblock %} - {{ sitename }}</title> <!-- ... snip ... --> <h1>{{ self.title() }}</h1> 
like image 190
Sean Vieira Avatar answered Oct 10 '22 07:10

Sean Vieira