【问题标题】:How to do a nested loop in Django如何在 Django 中进行嵌套循环
【发布时间】:2020-12-05 12:24:15
【问题描述】:

我正在尝试遍历我的选择字段表单并将每 4 个包围在 <div> </div> 中,这样每行只有 4 个选项。问题是我似乎无法弄清楚 django 中的嵌套循环。关于父循环的文档几乎没有,我也尝试过创建模板标签计数器但无济于事。

这是我正在使用的:

    {{ counter.count }}
    {% for check in form.pt_medical_condition %}
        
{% if counter.count == 4 %}
        <div>
        {% endif %}

    <label>
    {{ check.tag }} {{ check.choice_label }}
    </label>

        {% if counter.count == 4 %}
        </div>
        {% endif %}

{% if counter.count == 4 %}
{{ counter.count = 0 }}
{% endif %}
    {{ counter.increment }}
    {% endfor %}

有没有一种更简单的方法可以做到这一点,而不会看到我的模板标签无论如何都不起作用?谢谢!

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您可以尝试的一件事是使用自动递增的{{forloop.counter}},因此您不必尝试手动执行该部分。您也可以测试forloop.counter|divisibleby:4,而不是尝试每 4 次增量重置计数器。

    所以,类似:

    {% for check in form.pt_medical_condition %}    
        {% if forloop.counter|divisibleby:4 %}
            <div>
        {% endif %}
    
        <label>
            {{ check.tag }} {{ check.choice_label }}
        </label>
    
        {% if forloop.counter|divisibleby:4 %}
            </div>
        {% endif %}
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2019-07-28
      • 2020-07-28
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2017-09-01
      相关资源
      最近更新 更多