The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Droplet of life

--

Chapters
00:00 Question
00:47 Accepted answer (Score 440)
01:06 Answer 2 (Score 267)
01:20 Answer 3 (Score 77)
01:59 Thank you

--

Full question
https://stackoverflow.com/questions/1197...

Accepted answer links:
[If Expression]: https://jinja.palletsprojects.com/templa...

Answer 2 links:
[join]: https://jinja.palletsprojects.com/en/lat...

Answer 3 links:
https://jinja.palletsprojects.com/templa...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #jinja2

#avk47



ACCEPTED ANSWER

Score 463


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 else "" }}



ANSWER 2

Score 291


You could also use the builtin join filter like this:

{{ users|join(', ') }}



ANSWER 3

Score 85


And using the joiner from https://jinja.palletsprojects.com/templates/#joiner

{% set comma = joiner(",") %}
{% for user in userlist %}
    {{ comma() }}<a href="/profile/{{ user }}/">{{ user }}</a>
{% endfor %}  

It's made for this exact purpose. Normally a join or a check of forloop.last would suffice for a single list, but for multiple groups of things it's useful.

A more complex example on why you would use it.

{% set pipe = joiner("|") %}
{% if categories %} {{ pipe() }}
    Categories: {{ categories|join(", ") }}
{% endif %}
{% if author %} {{ pipe() }}
    Author: {{ author() }}
{% endif %}
{% if can_edit %} {{ pipe() }}
    <a href="?action=edit">Edit</a>
{% endif %}