51

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?

Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187

2 Answers2

100

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>
nosklo
  • 217,122
  • 57
  • 293
  • 297
4

The idea is to create a block inside a macro and then call macro two times, instead of having "block" tag repeated twice.

In latest Jinja2 version this works:

layout.html

{%- extends "base.html" -%}

{%- macro duplicated() -%}
    {% block overrideninchild %}{% endblock %}
{%- endmacro -%}

{% block base_content %}
    {{ duplicated() }}
    {{ duplicated() }}
{% endblock %}

child_page.html

{%- extends "layout.html" -%}

{% block overrideninchild %}
   Should be visible twice.
{% endblock %}
developer
  • 101
  • 2
  • 5
  • This is a good explanation and good to solve the "define once, use twice" task. But the other answer actually solve the "define once, show in both title and page" task which is more common. – Ben L Nov 17 '22 at 19:32