Django Tip: Templates and Page Titles

Posted on April 17, 2014, 9:15 p.m.

The core Django philosophy is DRY: do not repeat yourself. This quick tip will save you time and headaches when writing Django templates with page titles.

Let's start off with some assumptions. You have a parent template that you reuse throughout the site. Keep it simple and imagine these are the contents of site.html:

<head>
  <title>
    {% block title %}{% endblock %}
  </title>
</head>
<body>
  {% block body %}{% endblock %}
</body>

Now typically, you would use it with a child template, as shown below in child.html:

{% extends "site.html" %}

{% block title %}My page title{% endblock %}

{% block body %}
<h1>My page title</h1>
<p>My page content</p>
{% endblock %}

Or perhaps, your page content came from the database, as shown below in dyanmic_page.html:

{% extends "site.html" %}

{% block title %}{{ page.title }}{% endblock %}

{% block body %}
<h1>{{ page.title }}</h1>
<p>{{ page.content }}</p>
{% endblock %}

Simple. But we're repeating ourselves. Notice we wrote My page title twice.

Learning Django? Subscribe to my Django articles, tips and tutorials.

Fortunately, it turns out that Django actually outputs the contents of a {% block %} tag when you invoke it inside another {% block %} tag.

That means you can remove the duplicate titles, as shown below:

{% extends "site.html" %}

{% block body %}
<h1>{% block title %}My page title{% endblock %}</h1>
<p>My page content</p>
{% endblock %}

Or for the dynamic template, like so:

{% extends "site.html" %}

{% block body %}
<h1>{% block title %}{{ page.title }}{% endblock %}</h1>
<p>{{ page.content }}</p>
{% endblock %}

Simple as that. No more repeating yourself when adding page titles.

Tags: Django