【问题标题】:Django templates - include and repeat the block contentsDjango 模板 - 包含并重复块内容
【发布时间】:2018-11-19 05:40:00
【问题描述】:

在我的 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 %}

但是,它返回一个错误 - ''block' tag with name 'nav' 出现了不止一次'。

这是为什么呢?有什么解决办法吗?

问候

【问题讨论】:

  • 现在你不能在同名中添加两个块标签。尝试更改您的标签名称。更好的选择是包含所有在每个页面中保持相同的模板,并且只在您的正文中使用扩展标签。

标签: django django-templates include django-inheritance


【解决方案1】:

您在同一个模板中包含了两次 {% 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 %}

【讨论】:

  • 感谢您的回复。但我的问题是我是否可以在模板中多次重复使用块导航?
  • 不,据我所知你不能,原因是因为 {% block nav %} 正在用新数据替换另一个模板中同一块内的任何数据。当您包含它两次时,会导致模板混淆。既然您已经有了一个 id='footer-nav' 的 html div,为什么不在原始模板的该 div 中添加另一个块呢?这会让您在扩展模板时更清楚,因为您知道 {% block footer %} 指的是页脚 div。
猜你喜欢
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 2012-03-26
相关资源
最近更新 更多