jack rackham
jack rackham

Reputation: 19

How to iterate for loop in django python template

I am currently creating a template and I want to iterate a list however this is going to be tricky because I would like to display only 5 items per line then the next items will go to the next line. I would Like the display an image between every 5 items.

this is my list:

    myList = [{'id':1, 'image':'image1.jpg'},
{'id':2, 'image':'image2.jpg'},
{'id':3, 'image':'image3.jpg'},
{'id':4, 'image':'image4.jpg'},
{'id':5, 'image':'image5.jpg'},
{'id':6, 'image':'image6.jpg'},
{'id':7, 'image':'image7.jpg'},
{'id':8, 'image':'image8.jpg'},
{'id':9, 'image':'image9.jpg'},
{'id':10, 'image':'image10.jpg'},
{'id':11, 'image':'image11.jpg'},]

this is my template

myList.html

{% for a in myList %}

<a href="{{a.image}}">{{a.id}}</a>
{% if forloop.counter == 5%}
 <img src="{{a.image}}">
{% endif %}

{% endfor %}

and those images are link from each items.

this is what i would like to see

1 2 3 4 5
<image>
6 7 8 9 10
<image>
11

if I click each item, the image will display in the next line.

Here is a sample image on how it works IMAGE LINK

Upvotes: 0

Views: 107

Answers (2)

e-nouri
e-nouri

Reputation: 2626

You can use divisibleby like this: {% for a in myList %}

<a href="{{a.image}}">{{a.id}}</a>
{% if forloop.counter0|divisibleby:5 %}
 <img src="{{a.image}}">
{% endif %}

{% endfor %}

Link to the documentation.

Upvotes: 1

Nils Werner
Nils Werner

Reputation: 36849

You need to use the divisibleby filter

{% if forloop.counter0|divisibleby:5 %}

Upvotes: 1

Related Questions