How to add commas / separators for all list items except the last?

Say I have a for loop that contains a list of users. There can be 0-n Users in a loop. I want to put commas after every username except the last.

So for:

<p>
{% for u in users %}
{{u.name}},
{% endfor }
</p>

I get:

Sam, Neil, Bob,

I want to:

Sam, Neil, Bob
+3
source share
3 answers

I agree that this is a good approach. If you want to do this with, try

{% for u in users %}
{{u.name}}{% if not forloop.last %},{% endif %}
{% endfor }
+7
source

The for loop in Django 1.2 includes several automatically generated variables. Among them:

forloop.first
forloop.last

So you can put the separator using the if statement:

<p>
{% for u in users %}
{{u.name}}
{% if not forloop.last %}
,
{% endif %}
{% endfor %}
</p>
+2
source

, , "join" - , , .

, , :

{% with names = map(lambda u: u.name, users) %}
{{ names|join:", " }}
{% endwith %}
-1

Source: https://habr.com/ru/post/1786025/


All Articles