Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Template Arithmetic

In my template, I am looping through a list, trying to make a two-column layout. Because of the desired two-column layout, the markup I need to write in the for loop is dependent on whether forloop.counter0 is even or odd. If I had the full power of Python in the template language, determining the parity of forloop.counter0 would be trivial, but unfortunately that is not the case. How can I test whether forloop.counter0 is even or odd using the Django template language, or just as good, is there another way I could get elements in the list to display alternatively in the left and right columns?

Thanks in advance!

like image 566
Jonathan Gleason Avatar asked Jul 14 '26 00:07

Jonathan Gleason


2 Answers

You should probably use cycle here instead. As for your question, there is a filter called divisibleby.

The philosophy behind Django's template system is to avoid doing any serious logic in the template. Thus they only provide tools to do fairly basic calculations for cases like drawing grids etc.

like image 136
patrys Avatar answered Jul 16 '26 14:07

patrys


You can use the divisibleby filter with forloop.counter:

{% if forloop.counter|divisibleby:"2" %}even{% else %}odd{% endif %}
like image 39
msanders Avatar answered Jul 16 '26 12:07

msanders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!