Django模板-包含并重复块内容

时间:2018-11-19 05:40:00

标签: django django-templates include django-inheritance

在我的home.html页面中,我试图包括header.html文件以及扩展的base.html。以下是我的代码

{% extends "base.html" %}

{% block body %}
   {% include 'header.html' %}

   # including the block navigation from header.html
   <nav id='header-nav'>{% block nav %} {% endblock %}</nav>

   # including the block image from header.html
   <div id='header-img'>{% block image %} {% endblock %}</div>

   # Reusing the same navigation in footer from header.html
   <div id='footer-nav'>{% block nav %} {% endblock %}</div>

{% endblock %}

Home.html如下所示

{% block image %}<h1>I am image</h1>{% endblock %}
{% block nav %}<h1>I am navigation</h1>{% endblock %}

但是,它返回一个错误-名称为'nav'的'block'标签出现了多次'。

那是为什么?有什么解决办法吗?

致谢

1 个答案:

答案 0 :(得分:0)

您在同一模板中两次包含{%block nav%}。这就是它引发错误的原因。也许您打算做{%block footer%}?

{% extends "base.html" %}

{% block body %}
   {% include 'header.html' %}

   # including the block navigation from header.html
   <nav id='header-nav'>{% block nav %} {% endblock %}</nav>

   # including the block image from header.html
   <div id='header-img'>{% block image %} {% endblock %}</div>

   # Name this block something else i.e add a new block in header.html
   # and this error should clear up.
   <div id='footer-nav'>{% block footer %} {% endblock %}</div>

{% endblock %}