% Module in Django template

I am looking for a way to use something like a module operator in django. I am trying to add a class to every fourth element of the loop.

With the module, it will look like this:

{% 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 %} 

Of course, this does not work, because% is a reserved character. Is there any other way to do this?

+81
python django templates
Dec 13 '11 at 18:23
source share
4 answers

You need divisibleby , a built-in django filter.

 {% 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 %} 
+154
Dec 13 '11 at 18:42
source share

You cannot use the module operator in Django template tags, but it would be enough to write a filter to do this. Something like this should work:

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

And then:

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

Instead, you can do something like this:

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

And then:

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



Or you can use the cycle tag:

 <div class="post width1 height2 column {% cycle 'first' '' '' '' %}"> 
+11
Dec 13 '11 at 18:36
source share

Looks like you should just use a loop tag. Built-in Template Tags

+10
Dec 13 '11 at 6:41
source share

Example of rows and columns of the bootstrap. A new line every 4 items. Also close the last line, even if it is less than 4.

Myapp / templatetags / my_tags.py

 from django import template register = template.Library() @register.filter def modulo(num, val): return num % val 

html template

 {% 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 %} 
+2
Nov. '17 at 21:33
source share



All Articles