【问题标题】:python-django template-inheritance not working when referencing multiple blocks in basepython-django模板继承在引用基中的多个块时不起作用
【发布时间】:2018-09-29 11:42:25
【问题描述】:

我对 django 很陌生,正在尝试模板继承,但无法使其正常工作。我无法同时显示页面中的所有块。不确定我是否在 url、视图或设置中遗漏了某些内容。我在 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。但不知道如何让应用程序同时显示导航边栏

设置

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

【问题讨论】:

  • 最好在这里写代码而不是图像!

标签: python django django-templates


【解决方案1】:

首先要小心命名! 您正在 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 %}

【讨论】:

    猜你喜欢
    • 2021-01-10
    • 2021-12-10
    • 2015-11-30
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2013-01-09
    相关资源
    最近更新 更多