Django Template Arithmetic

一笑奈何 提交于 2019-12-07 22:59:53

问题


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!


回答1:


You can use the divisibleby filter with forloop.counter:

{% if forloop.counter|divisibleby:"2" %}even{% else %}odd{% endif %}



回答2:


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.




回答3:


Use cycle template tag:



来源:https://stackoverflow.com/questions/7571534/django-template-arithmetic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!