rix
rix

Reputation: 10632

Control in for loop in Django template

I don't know a lot about Django or Python, but I know it's problematic using a simple for loop in a template.

I'm wanting to do the following and wondering my options are - is there a simple way to do this in the template?

{% for image in my_images %}  //only loop through 1-10

Then:

{% for image in my_images %}  //only loop through 10-20

Thanks,

Upvotes: 1

Views: 255

Answers (2)

Constantine M
Constantine M

Reputation: 1547

If you need all the data but want to display it in chunks, you can split up your list like this

def Chunks(l, n):
    return [l[i:i+n] for i in range(0, len(l), n)]

where n=any number, in your case it would be 10

Then all you need to do is loop through the chunked list in the template.

Upvotes: 0

Gareth Latty
Gareth Latty

Reputation: 88977

If my_images is a list, you are looking for the slice filter:

{{ some_list|slice:":2" }}

If some_list is ['a', 'b', 'c'], the output will be ['a', 'b'].

Of course, on an optimization note, it would generally be better to do this at a view level by not fetching more records than you need.

Upvotes: 3

Related Questions