11

I have a fairly simple question, but I can't seem to find a simple solution to it. I'd like to iterate through an array in my Django template but skip the first value.

Let's say I have an array like this that I pass to my template through a view:

array = ['1', '2', '3', '4', '5']

In my template I do :

{% for a in array %} {{ a }} {% endfor %}

How can I do to only print '2' '3' '4' '5', without the first value ?

3 Answers 3

30
{% for a in array|slice:"1:" %}{{ a }}{% endfor %}

See https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#slice for more information.

Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly thanks. I'll look into this slice function, I didn't know about it
Having trouble with this when the array is a Queryset. I think @Some programmer dude's answer works more universally.
9
{% for a in array %}
  {% if not forloop.first %}
    {{ a }}
  {% endif %}
{% endfor %}

There is of course forloop.last for the last iteration as well.

They are all listed in the Django reference.

Comments

2
{% for a in array %}
{% if forloop.counter != 1 %}
    {{ a }}
{% endif %}
{% endfor %}

1 Comment

@Jeremy Lewis's solution is probably cleaner unless you want to do something with the first value

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.