在 Django 中,{{ block.super }} 出现问题,如何避免在多个模板文件中复制“块”?

e70*_*e70 1 django include django-templates

对于继承块的 2 个子模板文件,{{ block.super }}未解析

Python 2.5.2、Django 1.0、Windows XP SP3

所涉及文件的示例框架代码:

  1. base.html
  2. item_base.html
  3. show_info_for_all_items.html
  4. show_info_for_single_item.html

文件 : base.html

{% block content %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

文件 : item_base.html

{% extends "base.html" %}
{% block item_info %}   
    Item : {{ item.name }}<br/>
    Price : {{ item.price }}<br/>   
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

文件 : show_info_for_all_items.html

{% extends "item_base.html" %}
{% block content %}
    <h1>info on all items</h1>
    <hr/>
    {% for item in items %}
        {% block item_info %}
            {{ block.super }}
        {% endblock %}
        <hr/>
    {% endfor %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

文件 : show_info_for_single_item.html

{% extends "item_base.html" %}
{% block content %}
    <h1>info on single item</h1>    
    {% block item_info %}
        {{ block.super }}
    {% endblock %}  
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

show_info_for_all_items.html 显示项目列表以及每个项目的信息。

show_info_for_single_item.html 显示带有项目信息的单个项目。

show_info_for_all_items.htmlshow_info_for_single_item.html共享用于显示项目信息的相同代码,因此我将其item_base.html移至block item_info

{{ block.super }}inshow_info_for_all_items.htmlshow_info_for_single_item.html不起作用。{{ block.super }}解析为空白。

如果我移动代码从后面block item_infoitem_base.html进入show_info_for_all_items.htmlshow_info_for_single_item.html 它的作品,但后来我不得不重复相同block item_info的2个文件的代码。

如果无法解决 block.super 问题,Django 是否提供诸如 INCLUDE => 之类的功能,{% INCLUDE "item_base.html" %}以便可以包含模板文件中的块(而不是extends

如何避免block item_info在两个 html 文件中重复?

Dav*_*cos 5

Django 是否提供类似 INCLUDE (...)

是的!,看看文档:包括

将公共代码块放在foo.html 中,然后在每个模板中:

{% include 'foo.html' %}
Run Code Online (Sandbox Code Playgroud)