views:

749

answers:

2

For 2 child template files inheriting a block, the {{ block.super }} does not resolve

Python 2.5.2, Django 1.0, Windows XP SP3

Sample skeleton code for files involved:

  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 shows a list of items along with each item's info.

show_info_for_single_item.html shows a single item with the item's info.

show_info_for_all_items.html and show_info_for_single_item.html share same code for showing item info, so I moved it to item_base.html into block item_info

but the {{ block.super }} in show_info_for_all_items.html and show_info_for_single_item.html does not work. {{ block.super }} resolves as blank.

If I move the code back from block item_info in item_base.html into show_info_for_all_items.html and show_info_for_single_item.html it works but then I have to duplicate same block item_info code in 2 files.

If the block.super issue can not be solved, does Django offer something like INCLUDE => {% INCLUDE "item_base.html" %} so blocks from a template file can be included ( instead of extends )

How do I avoid duplicating block item_info in both html files?

+4  A: 

Does Django offer something like INCLUDE (...)

Yes!, just take a look at the documentation: include

Put the common code block in foo.html, and then, in each template:

{% include 'foo.html' %}
DZPM
+2  A: 

In addition to the include tag mentioned by DZPM, you might want to consider writing a http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags'>custom inclusion tag.

The main advantage in this case is that the calling template doesn't have to use the same variable names as the included template. You could show an item that is accessed from somewhere other than a variable named 'item':

{% show_item user.favorite_item %}
Matthew Marshall