Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test for use of a django template block?

I would like to do the following:

{% if appnav %}
<hr />
<div id="appnav">
    <ul class="tabs">
        {% block appnav %}{% endblock %}
    </ul>
</div>
{% endif %}

...however, testing for the present use of a block by templates further down the inheritance chain does not seem to work.

Is there some other conditional that might do this?

like image 851
Antonius Common Avatar asked Oct 27 '22 06:10

Antonius Common


1 Answers

The template language doesn't provide exactly what you're looking for. Child templates can call the parent block with {{ block.super }}, but parent templates can't reference child templates.

Your best bet will probably be to write a custom template tag. There are two sections in the template manual to review.

First, Parsing until another block tag. This will give you the basics of how to parse.

Second, Parsing until another block tag and saving contents. By placing a block tag inside the custom tag, you could detect content and wrap it as appropriate. This should work, because I believe the inner block tag will be parsed first. If that doesn't work, subclass the existing block template tag provided by django to implement your special magic.

like image 165
Jarret Hardie Avatar answered Nov 09 '22 11:11

Jarret Hardie