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

Fai*_*ith 3 django extends multiple-inheritance django-templates template-inheritance

我正在尝试创建 base.html 并在基础上加载几个名为“nav.html”、“contents.html”和“footer.html”的子模板。每当我访问 /base.html 时,我想让所有三个子模板都加载到 base.html 页面上。

基本.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>
Run Code Online (Sandbox Code Playgroud)

导航.html:

{% extends "base.html" %}

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

{% block nav %}
    <p>Here goes the nav</p>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

内容.html:

{% extends "base.html" %}

{% block contents %}
    <p>Here goes the contents</p>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

页脚.html:

{% extends "base.html" %}

{% block footer %}
    <p>Here goes the footer</p>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

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

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

def index(request):
    return TemplateResponse(request, "main/base.html")
Run Code Online (Sandbox Code Playgroud)

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

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

def index(request):
    return TemplateResponse(request, "main/nav.html")
Run Code Online (Sandbox Code Playgroud)

我无法加载其他两个子模板。我应该如何设置views.py文件,以便我可以通过仅加载/base.html来加载base.html上的所有三个子模板?(我认为不存在位置问题。我认为我陷入困境的是如何正确设置“views.py”以获得预期结果。)

Hen*_*son 5

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

{% block nav %}
    {% include "nav.html" %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

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