views:

1094

answers:

3

Hi all,

i have many fields in my form i was trying to apply different css to neighbour forms fields like

<li class='thiscolor' >
   <field>
</li>

<li class='thatcolor' >
   <field>
</li>

if there a way like

{% for field in form %}
    **{% if forloop.counter%2 == 0 %}**
   <li class='thiscolor'>
    {% else%}
   <li class='thatcolor'>     
    {%endif}
     {{field}}
    </li>
{% endfor %}

for forloop.counter ?

Thanks a lot!

+11  A: 

The cycle tag is designed for this type of problem:

{% for field in form %}
    <li class="{% cycle 'thiscolor' 'thatcolor' %}">{{ field }}</li>
{% endfor %}
Jarret Hardie
+4  A: 

I agree with Jarret that cycle is best here, but to actually answer the question, the %2==0 operation can be replicated by using the divisibleby filter.

{% if forloop.counter|divisibleby:"2" %}
Daniel Roseman
A: 

Another thing to keep in mind is that since this is a front end problem - the styling is what you're trying to effect - you can solve it on the front end. There's a good example provided toward the bottom of this A List Apart article. Of course, if you've already got working Django code there's no sense in doing this now.

bennylope
Yes, but templates are certainly the front-end portion of Django (the "V" in MVC).
DrBloodmoney
Right that, rather, it's a styling issue that can be alternately handled client side (CSS).
bennylope