python - Django forloop索引操作

标签 python django for-loop django-templates

我很难理解 Django 的 forloop.counter 是什么。我的目的是将 for 循环的每三个迭代包装在 <div> 中。我期望它如何工作是这样的:

{% for staff in staff_members %}
    {% if (forloop.counter + 2 % 3) == 0 %} // if loop is the first of three
    <div class="row">
    {% endif %}
        {{ staff }}

    // close <div class="row"> if loop is last of three
{% endfor %}

这不起作用,因为 Django 似乎不喜欢在 forloop.counter 上进行操作。在 View 中执行此操作似乎过于复杂,我宁愿在模板中执行此操作,因为这纯粹是一个表示/样式问题。

最佳答案

这与“Django不喜欢在柜台上操作”无关。只是 Django 的模板语言在设计上不支持对任何变量进行此类操作。

正如其他人所指出的,有些标签可以满足您的需求。最简单的方法可能是使用 divisibleby:

{% for staff in staff_members %}
    {% if forloop.counter|divisibleby:3 %}
    <div class="row">
    {% endif %}
    {{ staff }}
    {% if forloop.counter0|divisibleby:3 %}
    </div>
{% endfor %}

关于python - Django forloop索引操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19698115/

相关文章:

python - 如何从 Django 模板中当前经过身份验证的用户检查模型中是否存在记录?

javascript - 在 Django 中将输出从 javascript 发送到 html DIV

python - 为什么我的列表在我尝试 append 它们时没有加入 Python

python - Blender 3D 附加脚本加载失败

python - 如何处理导入错误?

Python/sklearn - preprocessing.MinMaxScaler 1d 弃用

python - 如何让Django管理命令不开启事务?

javascript - 错误 : [ng:areq] Argument 'GreetingController' is not a function, 未定义

ios - 如何在 Xcode 中使用 for 循环声明属性

python - 在 Python 中循环一个函数