我必须将一些 php 代码转换为 python django。在 django 中,我注意到很难做出像 php 那样的东西。
我必须通过**n(步)***迭代来增加一个简单的循环,
PHP 代码:
<?php $step = 3; for($i=0; $i < count($items); $i += $step){ /* */}
在 django 模板中:
我尝试了字典的 for
循环:
data['posts'] = {
"comments": [
{"id": "1", "title": "hey buddy"},
{"id": "2", "title": "hey buddy"},
{"id": "4", "title": "hey buddy"},
{"id": "5", "title": "hey buddy"},
{"id": "6", "title": "hey buddy"},
{"id": "7", "title": "hey buddy"},
{"id": "8", "title": "hey buddy"},
{"id": "9", "title": "hey buddy"},
]
}
在模板中:
for elem in posts.items:
{{ forloop.counter0|add:"3" }}
这可行,但它只是显示,没有将每次迭代的循环计数器设置为 3。
我希望每次迭代,循环都会增加指定的数字。
编辑 所以我想要的 django 模板结果是:
<div> the first 3 items </div>
<div> the next 3 items (so +3) </div>
<div> the final 3 items (+3) </div>
最佳答案
我没有在 django 中创建自定义标签就解决了,只是使用 divisibleby .
示例:
{% if forloop.counter0|divisibleby:3 %}
output items divide into 3 groups
{% endif %}
关于python - 问题 php 到 django 简单循环增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60189831/