Saturday 9th January 2010

by Stephen

When iterating over objects in a Python list in a Django template, it is nice to output a comma-separated list. This method also ensures that if only one object is output, it will not have a comma.

{% for item in list %}
{% if not forloop.first %}, {% endif %}
{{ item }}
{% endfor %}

If you had list = ['one'], this would output:

one

If you had list = ['one','two','three'], this would output:

one, two, three
· · · ◊ ◊ ◊ · · ·

Leave a Reply