首页 \ 问答 \ 检查一个值是否等于Django模板中另一个数字的模数(Check if a value is equal to the modulo of another number in a Django template)

检查一个值是否等于Django模板中另一个数字的模数(Check if a value is equal to the modulo of another number in a Django template)

我正在试图在Django中获得相同的结果

if idx % 3 == 2:做些什么

idx是forloop中的索引,但我简化了代码

我用这个:

{% ifequal idx|divisibleby:3 2 %}
    do something
{% endifequal %}

似乎divisibleby过滤器返回True所以在得到模数之后比较数字2几乎是不可能的。


I am trying to get an equivalent of this in Django

if idx % 3 == 2: do something

idx is an index in a forloop but I have simplified the code

I used this:

{% ifequal idx|divisibleby:3 2 %}
    do something
{% endifequal %}

It seems like the divisibleby filter returns True so it is almost impossible to compare the number 2 after getting its modulo.


原文:https://stackoverflow.com/questions/35528897
更新时间:2022-05-16 20:05

最满意答案

DivisibleBy只是做一个模数来检查最终值是否等于0,没有任何东西阻止你使用完全相同的代码制作自己的模板标签而没有最终检查

@register.filter(is_safe=False)
def modulo(value, arg):
    return int(value) % int(arg)


{% ifequal idx|modulo:3 2 %}

DivisibleBy just does a modulo to check whether or not the final value is equal to 0, there isn't anything stopping you making your own template tag using the exact same code without the final check

@register.filter(is_safe=False)
def modulo(value, arg):
    return int(value) % int(arg)


{% ifequal idx|modulo:3 2 %}

相关问答

更多