Tolga
Tolga

Reputation: 1357

how to use math remainder in django template?

I would like to change the class attribute of an li after each 4 elements (that means 5th, 9th, 13th li element classes should be changed).

I have tried something like below but it gave me an syntax error: Could not parse the remainder: '%4' from 'forloop.counter%4'

{% for p in plist %}
{% ifequal forloop.counter%4 1 %}
    <li class="clear"> {{p.title}} </li>
{% else %}
    <li> {{p.title}} </li>
{% endifequal %}
{% endfor %}

I will appreciate if somebody will suggest me a working solution.

Upvotes: 3

Views: 9973

Answers (5)

Jorge
Jorge

Reputation: 111

I struggled with this for a bit, trying to limit Bootstrap cards to 3 per card-deck.

This works in Django 2.1 and above, to limit a row to groups of 3:

{% ifequal forloop.counter|divisibleby:"3" True %}   

Upvotes: 4

Griffosx
Griffosx

Reputation: 1625

You can use forloop.counter0 and filter divisibleby:

{% ifequal forloop.counter0|divisibleby:"4" %}

Upvotes: 12

Andre Miller
Andre Miller

Reputation: 15533

You can't do evaluations like that in the django template. The ifequal tag expects only two parameters, and compares them. You would need some type of filter.

However, you could use the cycle tag instead:

{% for p in plist %} 
    {% if forloop.first %} 
        <li> {{p.title}} </li>
    {% else %}
        <li{% cycle '' '' '' ' class="clear"' %}> {{p.title}} </li> 
    {% endif %}
{% endfor %}

EDIT: As pointed out, the original solution cleared the 4, 8th, etc, instead of from the 5th onwards. I have updated the answer to include the changes by Tolga.

Upvotes: 5

Dominic Rodger
Dominic Rodger

Reputation: 99841

You don't want to do it like that - that's what cycle is for.

{% for p in plist %}
        <li{% ifnotequal forloop.counter 1 %}{% cycle ' class="clear"' '' '' '' %}{% endifnotequal %}>{{p.title}</li>
{% endfor %}

That example clears the 5th, 9th, 13th etc.

Edit: hat tip @cpharmston.

Upvotes: 1

c_harm
c_harm

Reputation:

The logic would be complex, but the divisibleby filter might help.

Upvotes: 2

Related Questions