【问题标题】:Django templates: make child loop inside of a nested loop to do certain number of iterationsDjango模板:在嵌套循环内制作子循环以进行一定数量的迭代
【发布时间】:2018-03-16 11:15:43
【问题描述】:

我有两个列表:

list1 = ['a','b','c','d']
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]

我想将它们渲染到模板中,如下所示:

a   1  2  3
b   4  5  6
c   7  8  9
d   10 11 12

因此,带有字母 (list1) 的第一列是行索引。每行包含 3 个由 list2 填充的单元格。

模板结构如下:

<div class="row">
   <div class="row-index">row index from list1</div>
   <div class="cell">cell1 from list2</div>
   <div class="cell">cell2 from list2</div>
   <div class="cell">cell3 from list2</div>
</div>

显然在这里做一个简单的嵌套嵌套循环是不够的(对于list1list2):

{% for row_index in list1 %}
   <div class="row">
      <div class="row-index">{{ row_index }}</div>
      {% for cell in list2 %}
      <div class="cell">{{ cell }}</div>
      {% endfor %}
   </div>
{% endfor %}

这将呈现 4 行(这是正确的!),但每行将有 12 个单元格,而不是每行 3 个。

不幸的是,zip_longest(list1, list2) 无济于事,因为它向list1 添加了额外的'None' 元素以使其与list2 的长度相等。结果是 4 个实际行索引,然后是 8 个空索引。对于每一行,渲染的单元格都是相同的,例如"a 1 1 1""b 2 2 2"

在 Django 模板中是否有任何方法可以强制子循环(在嵌套循环内)在其父循环的每 1 次迭代中只执行 3 次迭代?

【问题讨论】:

    标签: python django list loops django-templates


    【解决方案1】:

    将较长的列表分成块。您可以从this question 的答案中进行选择,例如:

    def chunks(l, n):
        """
        Yield successive n-sized chunks from l.
        code from https://stackoverflow.com/a/312464/113962
        """
        for i in range(0, len(l), n):
            yield l[i:i + n]
    

    将较短的列表和分块列表压缩在一起。

    list1 = ['a','b','c','d']
    list2 = [1,2,3,4,5,6,7,8,9,10,11,12]
    chunked = chunks(list2, 3)
    zipped_lists = zip(list1, chunked)
    

    然后循环遍历模板中的压缩列表,例如:

    {% for x, chunk in zipped_list %}
    {{ x }} {% for y in chunk %}{{ y }} {% endfor %}
    {% endfor %}
    

    【讨论】:

      【解决方案2】:

      你看过the forloop counter吗?

      {% for row_index in list1 %}
         <div class="row">
            <div class="row-index">{{ row_index }}</div>
            {% for cell in list2 %}
                 {% if forloop.counter < 4 %}
                     <div class="cell">{{ cell }}</div>
                 {% endif %}
            {% endfor %}
         </div>
      {% endfor %}
      

      【讨论】:

        猜你喜欢
        • 2011-05-20
        • 2021-11-30
        • 1970-01-01
        • 2012-01-21
        • 2014-10-22
        • 2012-10-25
        • 2021-06-05
        • 2014-12-23
        • 2013-05-09
        相关资源
        最近更新 更多