django 模板继承 - views.py 用于多个子模板

django template inheritance - views.py for multiple child templates

我正在尝试创建 base.html 并在基础上加载名为 "nav.html"、"contents.html" 和 "footer.html" 的几个子模板。每当我访问 /base.html.

时,我想让所有三个子模板都加载到 base.html 页面上

base.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>{% block title %}{% endblock %}</title>
  </head>

  <body>
    <nav class="navbar">
      <div class="nav">
        {% block nav %}{% endblock %}
      </div>
    </nav>

    <div class="content">
      {% block contents %}{% endblock %}
    </div>

    <div class="footer">
      {% block footer %}{% endblock %}
    </div>
  </body>
</html>

nav.html:

{% extends "base.html" %}

{% block title %}Page Title{% endblock %}

{% block nav %}
    <p>Here goes the nav</p>
{% endblock %}

contents.html:

{% extends "base.html" %}

{% block contents %}
    <p>Here goes the contents</p>
{% endblock %}

footer.html:

{% extends "base.html" %}

{% block footer %}
    <p>Here goes the footer</p>
{% endblock %}

现在,我的 views.py 看起来像:

from django.shortcuts import render
from django.template.response import TemplateResponse

def index(request):
    return TemplateResponse(request, "main/base.html")

它不会加载三个子模板中的任何一个,如果我加载其中一个子模板,例如

from django.shortcuts import render
from django.template.response import TemplateResponse

def index(request):
    return TemplateResponse(request, "main/nav.html")

我无法加载其他两个子模板。我应该如何设置 views.py 文件,以便我可以通过仅加载 /base.html 来加载 base.html 上的所有三个子模板? (我认为没有位置问题。我认为我卡住的地方是如何正确设置"views.py"以获得预期的结果。)

在您的块中使用 base.html 模板中的 #include 标签。

{% block nav %}
    {% include "nav.html" %}
{% endblock %}

这样,当您从 base.html 扩展新模板时,您将只覆盖块中的内容。