39

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

1

3 Answers 3

71

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

1
  • 1
    If you're using jinja2, this can be accomplished with {% for d in data %}{%if d == data|last %}{{ d }} {% else %}{{ d }}, {% endif %}{% endfor %} See last built-in function
    – GabLeRoux
    Commented Oct 27, 2014 at 3:26
13

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

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

1
  • Thank you. I knew the join filter. The example above was just a cooked up version to demonstrate what I mean.
    – Lim H.
    Commented Feb 13, 2013 at 17:28
12

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.