Lim H.
Lim H.

Reputation: 10050

Last element in django template list variable

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

Answers (3)

Aidan Ewen
Aidan Ewen

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

Love Sharma
Love Sharma

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

nicbou
nicbou

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

Related Questions