2008-11-21 28 views
1

對於2子模板文件繼承塊時,{{ block.super }}不能解決在Django中,{{block.super}}存在問題,我如何避免在多個模板文件中重複一個`block`?

的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

FILE:base.html

{% block content %} 
{% endblock %} 

FILE:item_base.html

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

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

FILE: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

show_info_for_all_items.html{{ block.super }}show_info_for_single_item.html不起作用。 {{ block.super }}解決爲空白。

如果我移動代碼回從block item_infoitem_base.htmlshow_info_for_all_items.htmlshow_info_for_single_item.html它的作品,但後來我有2個文件複製相同的block item_info代碼。

如果block.super問題不能得到解決,不Django的提供的東西等包括=>{% INCLUDE "item_base.html" %}所以從模板文件塊可以包括(而不是extends

如何避免在這兩個重複block item_info html文件?

+0

假如你的Django一派+包括你可能會問及在短的時間內回答了這個花了鍵入它in。 – 2008-11-22 01:31:54

回答

4

不Django的報價類似 包括:(......)

是的!只是來看看的文檔:include

把公共代碼塊FOO。HTML,然後,在每個模板:

{% include 'foo.html' %} 
2

除了由DZPM提到include標籤,你可能要考慮寫一個custom inclusion tag

這種情況下的主要優點是調用模板不必使用與包含的模板相同的變量名稱。你能證明是由超過一個名爲「項目」變量之外的其他地方訪問一個項目:

{% show_item user.favorite_item %} 
相關問題