Django模板中的模数% [英] Modulus % in Django template
本文介绍了Django模板中的模数%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种方法来使用像django中的模数运算符。我想要做的是为循环中的每个第四个元素添加一个类名。
I'm looking for a way to use something like the modulus operator in django. What I am trying to do is to add a classname to every fourth element in a loop.
对于模数,它将如下所示:
With modulus it would 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 doesn't work because % is a reserved character. Is there any other way to do this?
推荐答案
你需要 divisibleby ,一个内置的django过滤器。
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 %}
这篇关于Django模板中的模数%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文