0

我有一个打印一些元素列表的数组。我想在一组“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 %}
4

1 回答 1

2

在你看来,这是你真正应该做的工作。

在您看来:

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 或其他一些花哨的技巧来做到这一点,但这对于初学者来说是干净且易于理解的。

于 2012-12-12T18:27:15.857 回答