pajton
pajton

Reputation: 16246

Django template iterating over list

I have a list created in Django view:

list = [ elem1, elem2, ..., elemN ]

The list is variable length: it can contain 0-6 elements. I want to iterate over the list in the template, but I would like the loop to run always 6 times, yielding None or empty string for non-existing elements.

I tried something like this:

{% for i in "0123456" %}
    {{ list.i }}
{% endfor %}

but this obviously doesn't work. I know I could do this in the view, but I would like to have this in the template. Is is possible?

Upvotes: 1

Views: 8934

Answers (2)

markmywords
markmywords

Reputation: 663

You can add an if statement checking if it is your 6th time through the loop.

{% for item in someList %}
{% if forloop.counter <= 6 %}
{{ item }}
{% endif %}
{% endfor %}

http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#for in the docs. Of course, if your list is very long then this is not optimal. I would also suggest processing the list in views.py and then passing it to the template. Logic should stay in the views if possible.

This gives you control over the number of loops done. To completely solve your problem you will need some addtional logic but see my note above regarding this.

Upvotes: 2

arie
arie

Reputation: 18982

Check this snippet: Template range filter

Upvotes: 0

Related Questions