[英]issue with printing the elements of an array in django?
I have an array which prints the list of some elements. 我有一个数组打印一些元素的列表。 I want to print those elements in a group of say '4'. 我想在一组说“4”中打印这些元素。 That is if our array has 10 elements. 那就是我们的数组有10个元素。 Then in my template first <div>
shows first 4 elements and next <div>
shows next 4 elements. 然后在我的模板中,第一个<div>
显示前4个元素,下一个<div>
显示接下来的4个元素。 and so on. 等等。
I have tried to print like as we prints in PHP but it does not work here so please suggest me some way to do that. 我试图像在PHP中打印一样打印,但它在这里不起作用所以请建议我这样做的一些方法。
There are 9 products in c.list and i want to show them as i have mentioned above: c.list中有9个产品,我想按上面提到的那样显示它们:
{% if c.list|length >= 1 or c.list|length < 5 %}
{% for p in c.list %}
<div class="dis_box1">
<div class="item_imagebox_01"><a href="/shop/product/{{p.title}}"><img style ="width:145px;height:190px;"alt="" src="{{ MEDIA_URL }}{{p.image}}"></a>
<div class="img_line1"></div>
</div>
<div class="left"><span class="heart_text1"><a href="/shop/product/jhgjgj/">{{p.title}}</a></span></div>
</div>
{% endfor %}
{% endif %}
This is the kind of work you should really be doing in your view. 这是你应该在视图中真正做的工作。
In your view: 在你看来:
list_by_fours = []
list_len = len(c.list)
last_point = 0
next_point = 4
while last_point < list_len:
if next_point > list_len:
next_point = list_len
list_by_fours.append(c.list[last_point:next_point])
last_point += 4
next_point += 4
#Make sure you add list_by_fours to the template context
Then in your template: 然后在你的模板中:
{% for bucket in list_by_fours %}
{% for p in bucket %}
...
{% endfor %}
{% endif %}
I'm sure there's a way to do this with itertools or some other fancy trick, but this is clean and easy to understand for beginners. 我确信有一种方法可以用itertools或其他一些花哨的技巧来做到这一点,但对初学者来说这很简单易懂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.