1

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?

2 Answers 2

2

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.

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

1 Comment

I do not have long list to slice: I have a list that can have less than 6 elements and this is a problem.
0

Check this snippet: Template range filter

2 Comments

Thanks, that would work. Still I would prefer to use builtin tags/filters.
I don't think there is an easier builtin way to to this. Generally Django's approach is to put the logic in your views or in template tags and to keep the templates as clean as possible. Why do you have to construct the loop in your template?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.