[英]issue with printing the elements of an array in django?
我有一個數組打印一些元素的列表。 我想在一組說“4”中打印這些元素。 那就是我們的數組有10個元素。 然后在我的模板中,第一個<div>
顯示前4個元素,下一個<div>
顯示接下來的4個元素。 等等。
我試圖像在PHP中打印一樣打印,但它在這里不起作用所以請建議我這樣做的一些方法。
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 %}
這是你應該在視圖中真正做的工作。
在你看來:
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
然后在你的模板中:
{% for bucket in list_by_fours %}
{% for p in bucket %}
...
{% endfor %}
{% endif %}
我確信有一種方法可以用itertools或其他一些花哨的技巧來做到這一點,但對初學者來說這很簡單易懂。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.