Django has a problem with {{block.super}}. How to avoid duplicating a "block" in multiple template files?

For two child template files that inherit a block, {{ block.super }}

does not allow

Python 2.5.2, Django 1.0, Windows XP SP3

Sample skeleton code for the files involved:

  • base.html

  • item_base.html

  • show_info_for_all_items.html

  • 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 information for each item.

show_info_for_single_item.html

shows one item with information about the product.

show_info_for_all_items.html

and show_info_for_single_item.html

use the same code to display item information, so I moved it to item_base.html

inblock item_info

but {{ block.super }}

in show_info_for_all_items.html

and show_info_for_single_item.html

it does not work. {{ block.super }}

resolved as empty.

If I change the code back from block item_info

in item_base.html

to show_info_for_all_items.html

and show_info_for_single_item.html

, it works, but then I have to duplicate the same code block item_info

in 2 files.

If the block.super problem cannot be resolved, Django suggests something like INCLUDE => {% INCLUDE "item_base.html" %}

, so blocks from the template file can be included (instead of extends

)

How can I avoid duplication block item_info

in both html files?

+1


source to share


2 answers


Does Django offer something like INCLUDE (...)

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



Put a generic code block in foo.html and then in each template:

{% include 'foo.html' %}

      

+4


source


In addition to the tag include

mentioned by DZPM, you may need to write a custom include tag .

The main advantage in this case is that the calling template does not have to use the same variable names as the included template. You can show the item being accessed from somewhere other than a variable named "item":



{% show_item user.favorite_item %}

      

+2


source







All Articles