我在寻找一种在django中使用模运算符的方法.我试图做的是在循环中的每四个元素中添加一个类名.

使用模数,它看起来如下所示:

{% for p in posts %}
    <div class="post width1 height2 column {% if forloop.counter0 % 4 == 0 %}first{% endif %}}">
        <div class="preview">

        </div>
        <div class="overlay">

        </div>
        <h2>p.title</h2>
    </div>
{% endfor %}

当然,这不起作用,因为%是保留字符.有没有其他方法可以做到这一点?

推荐答案

你需要divisibleby%的内置Django 过滤.

{% for p in posts %}
    <div class="post width1 height2 column {% if forloop.counter0|divisibleby:4 %}first{% endif %}">
        <div class="preview">

        </div>
        <div class="overlay">

        </div>
        <h2>p.title</h2>
    </div>
{% endfor %}

Django相关问答推荐

Htmx如何从事件中访问数据?

在 Trunc 的 kind 属性中使用字段

Django: 无法将我的 comments 关联到特定产品

为什么 Django 在错误的目录中寻找模板?

反向 url django 管理员

在 Django 4.1 中提交表单之前显示数据

DecimalField 验证错误,返回不正确的值 Django

"" 需要有字段 "id" 的值才能使用这种多对多关系

在 settings.py 中指定 Django 测试数据库名称

将 **kwargs 传递给 Django 表单

相关字段查找无效:​​icontains

在 Django CharFields 中自动截断 max_length 字段

Django 基于角色的视图?

在生产中使用 Django 中的 SQLite?

Django 默认=timezone.now + delta

使用直通模型了解 Django 中的多对多字段

Django 应用程序中的版本号

显式 cursor.close() 的必要性

Django Admin - save_model 方法 - 如何检测字段是否已更改?

何时使用 Django get_absolute_url() 方法?