python - 问题 php 到 django 简单循环增加

标签 python django loops django-templates django-custom-tags

我必须将一些 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/

相关文章:

Python 如何在我下载视频时从 youtube-dl 获取下载百分比

django - 使用 Django 进行 Pagedown(Markdown 编辑器)

python - 如何读取本地存储中的文件(如内存中的文件)并将其附加到电子邮件中?

c++ - * 三角形图案设计问题

Python 使用 ssl.getpeercert() 从 URL 获取通用名称

python - 键盘中断与 python 的多处理池和映射函数

javascript - 在 react js中展开一个数组

c - C 中使用指针的 for 循环声明

python - pymysql : 2003, "Can' t 连接到 %r (%s) 上的 MySQL 服务器"% (self.host, e))

python - Django Apache mod_wsgi 权限错误