1

ブロックを継承する 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 %}

ファイル :item_base.html

{% extends "base.html" %}
{% block item_info %}   
    Item : {{ item.name }}<br/>
    Price : {{ item.price }}<br/>   
{% endblock %}

ファイル :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 %}

ファイル :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 %}

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.htmlblock item_info

しかし、動作{{ block.super }}しません。空白として解決されます。show_info_for_all_items.htmlshow_info_for_single_item.html{{ block.super }}

block item_infoコードを in からinitem_base.htmlに戻すshow_info_for_all_items.htmlと機能しますが、同じコードを 2 つのファイルshow_info_for_single_item.html に複製する必要があります。block item_info

block.super の問題を解決できない場合、Django は INCLUDE => のようなものを提供するので、テンプレート ファイルのブロックを ( の代わりに){% INCLUDE "item_base.html" %}含めることができますか?extends

block item_info両方の html ファイルで重複しないようにするにはどうすればよいですか?

4

2 に答える 2

5

Django は INCLUDE (...) のようなものを提供していますか?

はい、ドキュメントを見てください: include

共通コード ブロックをfoo.htmlに配置し、次に各テンプレートに配置します。

{% include 'foo.html' %}
于 2008-11-21T20:40:23.373 に答える
2

includeDZPM で言及されているタグに加えて、カスタムの包含タグの記述を検討することをお勧めします。

この場合の主な利点は、呼び出し元のテンプレートが含まれているテンプレートと同じ変数名を使用する必要がないことです。「item」という名前の変数以外の場所からアクセスされるアイテムを表示できます。

{% show_item user.favorite_item %}
于 2008-11-22T03:40:09.797 に答える