Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last element in django template list variable

Tags:

django

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

like image 635
Lim H. Avatar asked Feb 13 '13 17:02

Lim H.


2 Answers

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

like image 174
Aidan Ewen Avatar answered Oct 06 '22 23:10

Aidan Ewen


Use {{ data|join:", " }}, it does exactly what you need.

https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#join

like image 22
nicbou Avatar answered Oct 06 '22 23:10

nicbou