fox
fox

Reputation: 16506

How to chain {% includes %} in django templating

I have a base.html file that looks like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>

{% block header %}{% endblock %}

</head>
<body>

{% block content %}{% endblock %}

{% block footer %}{% endblock %}
</body>
</html>

and I have a file, auth.html that extends this:

{% extends "base.html" %}

{% block content %}

[MY CONTENT]

{% endblock %}

which works fine, but I also want to have a separate header.html file that plugs into the header block above.

What's the correct way to structure auth.html and header.html in order to include both and to have both extend base.html?

I tried adding a {% include header.html %} line to auth.html, and structuring header.html as follows:

{% extends "base.html" %}

{% block header %}

[HEADER CONTENT HERE]

{% endblock %}

but that didn't work. How should I be doing this?

Upvotes: 1

Views: 258

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

You need {{ block.super }}:

If you need to get the content of the block from the parent template, the {{ block.super }} variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it.

Its burried in the template inheritance documentation.


Suppose you want to add extra stuff to the header block in auth.html. header is defined in index.html:

Your auth.html would look like:

{% extends "index.html" %}

{% block header %}
{{ block.super }} 
Your extra stuff, which will come after whatever was in the header block
{% endblock %}

Upvotes: 2

Related Questions