Skip to content

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

2008 April 24
tags: ,
by pk

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 and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Posterous
  • Tumblr
  • Twitter

Comments are closed.