我有一个 base.html
文件,如下所示:
<!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>
我有一个文件 auth.html
扩展了这个:
{% extends "base.html" %}
{% block content %}
[MY CONTENT]
{% endblock %}
工作正常,但我还希望有一个单独的 header.html
文件插入上面的 header
block 中。
构建 auth.html
和 header.html
的正确方法是什么,以便包含两者并扩展 base.html
?
我尝试将 {% include header.html %}
行添加到 auth.html
中,并构建 header.html
如下:
{% extends "base.html" %}
{% block header %}
[HEADER CONTENT HERE]
{% endblock %}
但这没有用。我应该怎么做?
最佳答案
您需要{{ 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.
它被埋在template inheritance中文档。
<小时/>假设您想向 auth.html
中的 header
block 添加额外的内容。 header
在 index.html
中定义:
您的 auth.html
看起来像:
{% extends "index.html" %}
{% block header %}
{{ block.super }}
Your extra stuff, which will come after whatever was in the header block
{% endblock %}
关于python - 如何在 django 模板中链接 {% include %},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14868386/