Django Tips - Using empty in for loops

Django Tips - Using empty in for loops

/ #Django


There are different ways to check if a list is empty, but this is by far the best.

Sometimes, you need to check if a list is empty before you start looping through it. But is you just want to show when a list doesn't have any objects, then this {% empty %} is the way to go :-D

<div class="articles">
  {% for article in articles %}
    {% include 'partials/article.html' %}
  {% empty %}
    <p>No articles here...</p>
  {% endfor %}
</div>

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.