【问题标题】:django template inheritance - views.py for multiple child templatesdjango 模板继承-views.py 用于多个子模板
【发布时间】:2015-01-11 05:05:25
【问题描述】:

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

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

【问题讨论】:

    标签: django django-templates multiple-inheritance extends template-inheritance


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您让我获得新方法!现在我可以处理这个问题了。
    猜你喜欢
    • 2013-01-09
    • 2012-10-07
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 2011-02-04
    相关资源
    最近更新 更多