Multiple blocks of same name in Jinja2

Sridhar Ratnakumar picture Sridhar Ratnakumar · Aug 7, 2009 · Viewed 9.4k times · Source

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?

Answer

nosklo picture nosklo · Aug 7, 2009

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>