Django模板包含/块

时间:2018-10-09 22:42:49

标签: django django-templates

我具有以下模板结构:

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 %}   

filter.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.htmldetail.htmllist.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”。

1 个答案:

答案 0 :(得分:1)

从外观上看,您需要使用include标签而不是模板继承,即:

detail.html

{% extends "base.html" %}

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