如何在Django python temp中迭代for循环

2024-05-15 19:49:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在创建一个模板,我想迭代一个列表,但这将是棘手的,因为我想显示每行只有5个项目,然后下一个项目将转到下一行。我想在每5个项目之间显示一个图像。你知道吗

这是我的清单:

    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'},]

这是我的模板

你知道吗myList.html文件你知道吗

{% for a in myList %}

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

{% endfor %}

这些图片是每个项目的链接。你知道吗

这就是我想看到的

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

如果单击每个项目,图像将显示在下一行中。你知道吗

这是一个关于它如何工作的示例图像IMAGE LINK

  • 如果单击数字1,图像1将显示在绿色框中 2号到5号也是这样。你知道吗
  • 如果单击数字9,图像9将显示在绿色框中, 数字6到数字6的方法相同 10你知道吗

Tags: 项目图像image模板id列表数字jpg
2条回答

您需要使用divisibleby过滤器

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

可以这样使用divisibleby: {%在myList%}

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

{% endfor %}

Link到文档。你知道吗

相关问题 更多 >