It looks like your layout is solid. You have a base.html
template that defines the basic structure and outer layout for each page in your app. You also have base_object.html
that extends this template.
You'd like each page to have a unique title and a matching h1 (I think). This best way to do this is to define two separate blocks in your base.html template.
<html>
<head>
<title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
<h1>{% block h1 %}{% endblock %}</h1>
</body>
</html>
In your child templates, you need to override both of these if you'd like them to be identical. I know you feel this is counter-intuitive, but it is necessary due to the way template inheritance is handled in Django.
Source: The Django template language
Finally, note that you can't define multiple {% block %}
tags with the same name in the same template. This limitation exists because a block tag works in "both" directions. That is, a block tag doesn't just provide a hole to fill -- it also defines the content that fills the hole in the parent. If there were two similarly-named {% block %}
tags in a template, that template's parent wouldn't know which one of the blocks' content to use.
The children look like this:
{% extends "base.html" %}
{% block title %}Title{% endblock %}
{% block h1 %}Title{% endblock %}
If this bothers you, you should set the title from the view for each object as a template variable.
{% block title %}{{ title }}{% endblock %}
{% block h1 %}{{ title }}{% endblock %}
Django strives to keep as much logic out of the template layer as possible. Often a title is determined dynamically from the database, so the view layer is the perfect place to retrieve and set this information. You can still leave the title blank if you'd like to defer to the default title (perhaps set in base.html
, or you can grab the name of the site from the django.contrib.sites
package)
Also {{ block.super }}
may come in handy. This will allow you to combine the contents of the parent block with additional contents from the child. So you could define a title like "Stackoverflow.com" in the base, and set
{% block title %}{{ block.super }} - Ask a Question{% endblock %}
in the child to get a title like "Stackoverflow.com - Ask a Question"