首页 > 解决方案 > Django 模板包含/块

问题描述

我有以下模板结构:

base.html:

<html>
  <head>
  </head>
  <body>
    <div class="main-content">
      {% block body %}{% endblock %}
    </div>
  </body>
</html>

detail.html扩展 base.html:

{% extends "base.html" %}

{% block body %}
    <!-- filter side panel -->
    {% block filter_panel %}
    {% endblock %}
{% endblock %}

list.html扩展 base.html:

{% extends "base.html" %}

{% block body %}
    <!-- filter side panel -->
    {% block filter_panel %}
    {% endblock %}
{% endblock %}   

过滤器.html:

{% extends "detail.html" %}
{% block filter_panel %}
  ...
  ...
{% endblock%}

现在,我已经实现了一个过滤器面板,它由一个按钮调用,使用onclick="filter_open()". 相应的方法在一个外部 JS 文件中,基本上打开一个侧面板:

function filter_open() {
  document.getElementById("filtersidebar").style.display = "block";
  document.getElementById("filtersidebar-outer").classList.add("fc-filters-overlay");
}

这个过滤器,我想在 detail.html 和 list.html 上提供。所以,我创建了一个新文件filter.html。thedetail.html和 thelist.html都有一个{% block filter %}{% endblock %},并且filter.html我在各自的 Django 块中添加了功能。

但是,该按钮现在会引发错误:

Uncaught TypeError: Cannot read property 'style' of null
  at filter_open (main.js:146)
  at HTMLButtonElement.onclick ((index):158)

我想这是因为我将过滤器移到了“filter.html”。

标签: djangodjango-templates

解决方案


从它看起来你需要的是使用include标签而不是使用模板继承,即:

详细信息.html

{% extends "base.html" %}

{% block body %}
    <!-- filter side panel -->
    {% include "filter.html" %}
{% endblock %}

推荐阅读