Saturday, September 18, 2010

Django: empty clause in for loop

One thing I like about Jinja is the else clause in the for ... in loop syntax. It handy when you want to display something like "Your cart is empty ..." when looping through a list of items, if the items is empty.

It not obvious in the documentation but after searching around, I found out that Django also had the same functionality now in changeset 9530. That's about 2 years ago, so much things I miss in Django world. Django use the keyword "empty" rather than "else" as in Jinja.

{% for item in items %}
...
{% empty %}
Your cart is empty
{% endfor %}

No comments: