Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple blocks of same name in Jinja2

In Jinja2, I have a base template like this:

<title>{% block title %}{% endblock %} - example.com</title> [...]  <h1>    {% block title %}{% endblock %} - example.com </h1> 

Jinja2, then, fails with the following message:

  lines = [self.message, '  ' + location] : block 'title' defined twice 

It must be now evident as to what I am trying to do - to have the same title in two places: the TITLE tag and the H1 tag, but the part of the title is actually provided by other derived templates.

How does one typically achieve this?

like image 702
Sridhar Ratnakumar Avatar asked Aug 07 '09 00:08

Sridhar Ratnakumar


People also ask

What is the difference between Jinja and Jinja2?

Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.

How do you write a for 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.


1 Answers

As documented here, defining a block creates a macro with the name of the block in the special "self" object:

<title>{% block title %}{% endblock %} - example.com</title> [...]  <h1>    {{ self.title() }} - example.com </h1> 
like image 180
nosklo Avatar answered Sep 21 '22 16:09

nosklo