1

我必须将一些 php 代码转换为 python django,在 django 中我注意到很难像 php 那样做:

我的问题是,我必须通过n ( step) *迭代来增加一个简单的循环,

php代码:

<?php $step = 3; for($i=0; $i < count($items); $i += $step){ /* */}

在 django 模板中:我尝试了字典的循环,

   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>

谢谢

4

1 回答 1

1

我没有在 django 中创建自定义标签就解决了,只是使用了divisibleby 示例:

{% if forloop.counter0|divisibleby:3 %} output items divide into 3 groups {% endif %}

于 2020-02-12T15:19:15.600 回答