python - 如何在 django 模板中链接 {% include %}

标签 python html django

我有一个 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.htmlheader.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 添加额外的内容。 headerindex.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/

相关文章:

html - 带有 rowspan 的粘性 td(标题)

Django 在页面之间传递查询集

django - 获取 pkg_resources.DistributionNotFound : The 'supervisor==3.2.0' distribution was not found and is required by the application?

python - 如果满足某些条件,Django 中间件为 'do nothing'

Python 解释器占用了我 130% 的 CPU。这怎么可能?

python - Ubuntu Python : unable to pip install dlib - Failed building wheel for dlib and machine is almost stuck

javascript - 通过 aria 标签获取 HTML 元素

javascript - 关注下一个输入不起作用以及当用户在最后一个输入字段时如何提交表单

python - matplotlib 中带箭头的线图

python - 异常后如何重试?