Django - 一个模板可以扩展两个或多个模板吗?

Django - Can two or more templates be extended by one template?

假设有 base_a.htmlbase_b.htmla.htmlb.htmlc.html

a.html 扩展了 base_a.html 并且 b.html 扩展了 base_b.html.
c.html 必须同时扩展 base_a.htmlbase_b.html.

如果你认为base_a.html包含回复功能而base_b.html包含搜索功能,那么这种情况就更容易理解了。

我可以在 Django 模板中使用多重继承吗?
还是我必须使用 include 而不是 extends?

docs

所述

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

也就是说第二行不能放一个{% extends %}标签,即不能有两个{% extends %}标签。

您的案例可以通过 {% include %} 标签轻松解决。例如:

a.html中:

{% include 'base_a.html' %}

b.html中:

{% include 'base_b.html' %}

c.html中:

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

当然,base_a.htmlbase_b.html 应该只包含您要重复使用的特定块,而不是完整的 HTML 模板。

是的,您可以扩展不同或相同的模板。

例如:

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

    <h1>Content goes here</h1>

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