Django Tip: Templates and Page Titles

Posted on 2014-04-18 01:15:00+00:00

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

Comments

Donovan Wilson2015-07-02 14:35:50+00:00

So how do I get page titles from the database?

Reply
Donovan Wilson2015-07-02 14:36:09+00:00

by the way thanks for this post.

Reply
Donovan Wilson2015-07-02 14:38:16+00:00

For example what if the page is a list? Can you store all the titles in one place?

Reply
Dror2016-05-13 07:16:04+00:00

Where is the value of "page.content" coming from ?

Reply
silviogutierrez2016-05-13 23:30:52+00:00

From whatever context you called when rendering the template. Could be an object you retrieved from the database using generic views.

See: https://docs.djangoproject.com/en/1.9/ref/class-based-views/generic-display/#detailview

Reply
Seth Livingston2017-07-30 15:45:20+00:00

This is great; thank you.

Reply

Post New Comment