Can multiple templates be extended by one template in Django?

21k Views Asked by At

Let's say there are base_a.html, base_b.html, a.html, b.html, c.html.

a.html extends base_a.html and b.html extends base_b.html.
And c.html has to extend both base_a.html and base_b.html.

It will be easier to understand this situation if you think base_a.html contains reply functionalities and base_b.html contains search functionalities.

Can I use multiple inheritance in Django template?
Or do I have to use include instead of extends?

3

There are 3 best solutions below

1
On BEST ANSWER

As stated at the docs,

If you use {% extends %} in a template, it must be the first template tag in that template.

That suggests that an {% extends %} tag cannot be placed in the second line, that is, you cannot have two {% extends %} tags.

Your case can easily be solved with {% include %} tags. For example:

In a.html:

{% include 'base_a.html' %}

In b.html:

{% include 'base_b.html' %}

In c.html:

{% include 'base_a.html' %}
{% include 'base_b.html' %}

Of course, base_a.html and base_b.html should only contain the specific block you want to reuse, not a full HTML template.

1
On

In addtion to other answers, one template can extend only one template with {% extends %} but not multiple templates.

So, if one template tries to extend multiple templates with {% extends %} as shown below:

# "templates/index.html"

{% extends "base1.html" %}
{% extends "base2.html" %}

Then, the error below occurs:

'extends' cannot appear more than once in the same template

0
On

Yes you can extend different or same templates.

For example:

{% extends "base.html" %}
{%     block content     %}

    <h1>Content goes here</h1>

{% include 'base.html' %}
{% endblock %}

multiple template in same page