[Django]-Check if a value is equal to the modulo of another number in a Django template

5👍

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 %}
👤Sayse

2👍

idx % 3 == 2 exactly if (idx - 2) % 3 == 0

Thus

{% if idx | add:-2 | divisibleby:3 %}
    do something
{% endif %}

should do what you want, I think.

👤das-g

1👍

You’re correct, divisbleby will only return True or False so besides building your own template tag like @sayse suggested you could also provide a set of numbers x where x % 3 ==2 and then just compare in your template like this:

In your views context['correct_numbers'] = { x for x in range(100) if x%3 ==2}

Then in your template:

{% if idx in correct_numbers %}
    do something
{% endif %}

Leave a comment