Django Tip: Outputting list of items separated by commas, but only if it has more than one item

by pk on April 24, 2008

How many times do you need to do this? You have a list of things to output. The list can be empty, has one element, or more. You want to separate each items with a separator for readability. What do you do?

1. The simple but not reader friendly way:

toppings = [ 'cheese','tomatos','pineapple' ]
or toppings = ['cheese']

{% for t in toppings %}
{{ t }} ,
{% endfor %}

that will output:
cheese, tomatos, pineapple,

or

cheese,

Note the ugly trailing comma.

2. This is the smart way using the template variables available in loops:

{% for t in toppings %}
{% if not forloop.first %}, {% endif %}
{{ t }}
{% endfor %}

that will output:
cheese, tomatos, pineapple

or

cheese
No more trailing commas, thanks to the built in forloop variables.

  • Share/Bookmark

Comments on this entry are closed.

Previous post: IKEA Tool Box Hack

Next post: Django Tip: No leading slash for upload_to for FileField and ImageField