python-django模板继承在引用base中的多个块时不起作用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-django模板继承在引用base中的多个块时不起作用相关的知识,希望对你有一定的参考价值。
我是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的建议,但还没能让它工作。感谢这里的任何帮助。
首先要注意命名!您正在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 %}
以上是关于python-django模板继承在引用base中的多个块时不起作用的主要内容,如果未能解决你的问题,请参考以下文章