python-django模板继承在引用base中的多个块时不起作用

时间:2018-04-19 05:09:29

标签: python django django-templates

我是django的新手,我正在尝试模板继承,但无法让它工作。我无法同时显示页面中的所有块。不确定我是否遗漏了网址,视图或设置中的内容。我在PyCharm上使用Python 3.6 in venv / Django 2.0.4

下面我的例子的详细信息 - myhome是项目名称,smarthome是app name

文件夹结构

base.html文件

navtopbar.html

navsidebar.html

smarthome urls.py

smarthome views.py

- 最初我将此作为base.html,但根据以下主题中的建议,更改为navtopbar。但后来不确定如何让应用程序同时显示navsidebar

设置

我按照this thread中的建议,但未能使其工作。感谢这里的任何帮助。

1 个答案:

答案 0 :(得分:0)

首先要小心命名! 您正在navtopbar.html

中呈现自己的观点

navtopbar.html中,您只覆盖navtopbar块,因此只会替换该块。

Djnago模板的工作原理如下:

<强> base.html文件

{% block body %} base {% endblock %}
{% block content %} base {% endblock %}

现在,如果从视图中呈现home.html,它应该是:

<强> home.html的

{% extends 'base.html' %}
<!-- the blocks you override here only replaced -->
{% block body %}
home
{% endblock %}

如上面的html,你只覆盖了一个块,它会覆盖一个块而其他块保持不变。如果要覆盖{% block content %},则需要覆盖以下相同的html:

<强> home.html的

{% extends 'base.html' %}
<!-- the blocks you override here only replaced -->
{% block body %}
home
{% endblock %}
{% block content %}
home content
{% endblock %}

如果您想要包含其他html中的内容,可以将其与include代码

一起添加

请考虑以下文件:

<强> content.html

<h3>This is common content</h3>

现在您可以在home.html中添加此内容,如下所示:

<强> home.html的

{% extends 'base.html' %}
<!-- the blocks you override here only replaced -->
{% block body %}
home
{% endblock %}
{% block content %}
    {% include 'content.html' %}
{% endblock %}
相关问题