ChatGPT解决这个技术问题 Extra ChatGPT

Django模板中的模数%

我正在寻找一种在 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 %}

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

你甚至尝试过吗? Django 提供了 templatetag 标记,但它涵盖了 {%%} 等(不是 %)。
是的,我试过了,但我得到了以下错误: 无法解析余数:来自 '%' 的 '%' 我认为这是因为它不知道如何削减模数。该运算符也未在文档中列出 docs.djangoproject.com/en/dev/ref/templates/builtins/…

B
Burhan Khalid

您需要 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 %}

啊,是的,就是这样。现在使用循环,但有利于将来参考。我不想将循环与模 100 或其他东西一起使用:) 实际上我要把这个答案标记为正确的答案。因为它专注于模数而不是解决方法......
m
mipadi

您不能在 Django 模板标签中使用模数运算符,但编写一个过滤器来这样做很容易。像这样的东西应该工作:

@register.filter
def modulo(num, val):
    return num % val

接着:

{% ifequal forloop.counter0|modulo:4 0 %}

你甚至可以做这样的事情,而不是:

@register.filter
def modulo(num, val):
    return num % val == 0

接着:

{% if forloop.counter0|modulo:4 %}

或者您可以使用 cycle 标记:

<div class="post width1 height2 column {% cycle 'first' '' '' '' %}">

a
ab 16

引导行和列示例。每 4 项新行。即使少于 4 个项目,也要关闭最后一行。

myapp/templatetags/my_tags.py

from django import template

register = template.Library()

@register.filter
def modulo(num, val):
    return num % val

html模板

{% load my_tags %}

{% for item in all_items %} 
    {% if forloop.counter|modulo:4 == 1 %}
        <div class="row">
    {% endif %}

        <div class="col-sm-3">
            {{ item }}
        </div>

    {% if forloop.last or forloop.counter|modulo:4 == 0 %}
        </div>
    {% endif %}

{% endfor %}

这是更好的答案,因为它描述了需要创建的目录,并且还描述了在模板 html 中加载自定义模板的需要。谢谢你。
因此,如果我有与此相同的设置,将我的小程序移动到我的 settings.py 的已安装应用程序中,重置我的服务器,可以从 shell 访问模板标签,像你一样在模板中加载标签,为什么可以'我不使用模数!?!?我一直按照 Django 教程进行操作。
s
spacediver

听起来您应该只使用循环标签。 Built-in template tags