3

我正在尝试创建 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>

导航.html:

{% extends "base.html" %}

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

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

内容.html:

{% extends "base.html" %}

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

页脚.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”以获得预期的结果。)

4

1 回答 1

5

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

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

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

于 2015-01-11T05:07:57.237 回答