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.
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.
For example what if the page is a list? Can you store all the titles in one place?
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