How to output a comma delimited list in jinja python template?

Rolando picture Rolando · Aug 15, 2012 · Viewed 110.3k times · Source

If I have a list of users say ["Sam", "Bob", "Joe"], I want to do something where I can output in my jinja template file:

{% for user in userlist %}
    <a href="/profile/{{ user }}/">{{ user }}</a>
    {% if !loop.last %}
        , 
    {% endif %}
{% endfor %}   

I want to make the output template be:

Sam, Bob, Joe

I tried the above code to check if it was on the last iteration of the loop and if not, then don't insert a comma, but it does not work. How do I do this?

Answer

Joe Day picture Joe Day · Aug 15, 2012

You want your if check to be:

{% if not loop.last %}
    ,
{% endif %}

Note that you can also shorten the code by using If Expression:

{{ ", " if not loop.last }}