Search code examples
pythondjangodjango-templatesdjango-template-filters

Only render part of django template if objects.all is not empty


I only want to render part of a django template if objects.all is not empty. Normally this is done like:

<ul>
{% for thing in things.all %}
    <li>{{ thing.name }}</li>
{% empty %}
    <li>Sorry, nothing to see here</li>
{% endfor %}
</ul>

But what if I want to have a heading or something that only shows if there's something to put in the list? I don't want the heading to be repeated each time the for loop runs. Is there something like {% not empty %} I could use, e.g.:

{% if things.all not empty %}
<h1>Things</h1>
<ul>
{% for thing in things.all %}
    <li>{{ thing.name }}</li>
{% endfor %}
</ul>

The above, however, throws a TemplateSyntaxError for django Not expecting 'not' as infix operator in if tag.

How can we check if something is empty before running the loop?


Solution

  • Figured it out. This check can be run by simply excluding the not empty clause:

    {% if things.all %}
    <h1>Things:</h1>
    <ul>
    {% for thing in things.all %}
        <li>{{ thing.name }}</li>
    {% endfor %}
    </ul>
    

    No TemplateSyntaxError, and the <h1> is only printed once, before the loop, and only if there's something to list in the loop.