简体   繁体   English

如何在Django Python模板中迭代循环

[英]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. 我当前正在创建一个模板,并且想要迭代一个列表,但是这很棘手,因为我想每行仅显示5个项目,然后下一个项目将转到下一行。 I would Like the display an image between every 5 items. 我希望在每5个项目之间显示一个图像。

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 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 这是有关其工作方式的示例图片 IMAGE LINK

  • If number 1 is clicked the image1 will be shown in the green box, the same way for number 2 to number 5. 如果单击数字1,则图像1将显示在绿色框中,数字2到数字5的显示方式相同。
  • If number 9 is clicked the image9 will be shown in the green box, the same way for number 6 to number 10. 如果单击数字9,则图像9将显示在绿色框中,数字6到数字10的显示方式相同。

您需要使用divisibleby过滤器

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

You can use divisibleby like this: {% for a in myList %} 您可以使用divisibleby {在myList中%%一}:像这样的

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

{% endfor %}

Link to the documentation. 链接到文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM