Django Tips & Tricks #5 - Use for...empty in Django templates


It is quite common to send a query set from a view to template, loop over it and display items in it. If no items are there, it is good if we display some message. For that we can do something like this.
{% if books %}
{% for book in books %}
<li>{{ book }}</li>
{% endfor %}
{% else %}
<li>Sorry, there are no books.</li>
{% endif %}
Django {% for %} tag takes an optional {% empty %} clause which will be rendered when queryset is empty. So we can rewrite the above code as
{% for book in books %}
<li>{{ book }}</li>
{% empty %}
<li>Sorry, there are no books.</li>
{% endfor %}
This code is much cleaner than previous one. I tried to profile both code blocks. The first block took 0.9ms and second block took 0.8ms which means it is 11% faster than previous code :)
Reference: Django docs

Comments

Comments powered by Disqus