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

问题描述 投票:-1回答:1

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

下面我的例子的详细信息 - myhome是项目名称,smarthome是应用程序名称

文件夹结构

base.html文件

navtopbar.html

navsidebar.html

smarthome urls.py

smarthome views.py

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

设置

我遵循了this thread的建议,但还没能让它工作。感谢这里的任何帮助。

python django django-templates
1个回答
0
投票

首先要注意命名!您正在navtopbar.html中呈现您的视图

navtopbar.html中,你只有覆盖navtopbar块,所以只有那个块才会被替换。

Django模板的工作原理如下:

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 %}
© www.soinside.com 2019 - 2024. All rights reserved.