Skip to content
Sep 5 / PK Shiu

Django template: putting commas between a list of items

This is a very common usage pattern. You have a list of items for display, perhaps a list of tags. The list can have zero, one or more items. How do you, using the Django template language, put commas between each item?

1. This simple way will not produce good result for a list of one item:


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
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Twitter
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • Google Buzz
  • LinkedIn
  • Tumblr
  • Reddit

6 Comments

Leave a comment
  1. Brandon Taylor / Jan 4 2011

    Why not simply use the join template filter?

    {{ toppings|join:”, ” }}

    It will handle omitting the comma and space for the final iteration through the loop.

  2. Trever Shick / Jan 4 2011

    I prefer to use “join” for that.
    >>> l = [1,2,3]
    >>> “,”.join([str(x) for x in l])

    or in Django’s template language

    {{ value|join:”,” }}

  3. PK Shiu / Jan 4 2011

    Thanks Trever and Brandon on the tips for using “join” instead!

  4. Aaron Sinclair / Aug 12 2012

    Just what I was looking for. I can’t use join because I’m adding tags to a blog, I want each item in the array to be wrapped in an anchor tag but need commas between each of them (although I didn’t know about join until this post either :D)

  5. Japan Shah / Nov 2 2012

    Nice solution

    Keep blogging & keep commenting 🙂

  6. Jay / Jul 29 2014

    {{toppings|printList}}

    then create a filter:

    @register.filter
    def printList(value):
    if value and len(value) > 1:
    return str(“, “.join(value[:-1])) + ” and ” + str(value[-1])
    else:
    return value

Leave a comment