Reputation: 10050
I would like to know how to filter out the last element of a list variable from the context object.
{% for d in data %}
{{ d }},
{% endfor %}
I don't want to have the ,
after the last element. Thank you.
NOTE: This is just a hypothetical example. I know we can use the join filter to achieve the same thing here
Upvotes: 39
Views: 23142
Reputation: 13308
Do you mean -
{% for d in data %}
{% if forloop.last %}
{{ d }}
{% else %}
{{ d }},
{% endif %}
{% endfor %}
have a look at the django docs on template for loops
Upvotes: 71
Reputation: 1999
Or you can try this as well -
{% for d in data %}
{{ d }} {% if not forloop.last %},{% endif %}
{% endfor %}
have a look at the docs on template for loops
Upvotes: 12
Reputation: 1056
Use {{ data|join:", " }}
, it does exactly what you need.
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#join
Upvotes: 13