Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulus/Modulo equivalent operator/function in django templates?

I'm just learning django's templating system and trying to do something relatively trivial:

<h2>State</h2>
<ul class="states">
{% for state in states %}
   <li class="state_elements" ><a href="/{{ state.name }}/"> {{ state.name }}</a></li>
   {% if forloop.counter \% 3 == 0 %}
   <br style="clear: both"/>
 {% endif %}
{% endfor %}
</ul>

I get a syntax error because % is a symbol reserved for the templating language. This is unfortunate.

I already found a partial solution with

{% cycle "" "" "" '<br style="clear: both"/>' %}

but it strikes me as damn odd. Is there a better way?

like image 598
David Avatar asked Nov 13 '11 05:11

David


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {{ NAME }} mean in Django templates?

8. What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

Is equal in Django template?

If the values of these variable are equal, the Django Template System displays everything between the {% ifequal %} block and {% endifequal %}, where the {% endifequal %} block marks the end of an ifequal template tag.

What is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.


2 Answers

forlopp count divisible by 2

{% if forloop.counter|divisibleby:2 == 0 %}

forloop count not divisible by 2

{% if forloop.counter|divisibleby:2 != 0 %}
like image 67
Jhanvi Patel Avatar answered Oct 15 '22 20:10

Jhanvi Patel


divisibleby

Returns True if the value is divisible by the argument.

For example:

{{ value|divisibleby:"3" }}

django template doc

like image 35
iMom0 Avatar answered Oct 15 '22 19:10

iMom0