Perhaps this is a non-question, but how do you make use of the Django {% cycle %}
functionality, or something similar, when you're not in a loop? Specifically, I have an HTML table that I'm writing by hand, since it's not the sort of thing you need to do in a loop. I want the rows to alternate, like this:
<tr class="{% cycle 'even' 'odd'%}"></tr>
<tr class="{% cycle 'even' 'odd'%}"></tr>
<tr class="{% cycle 'even' 'odd'%}"></tr>
But I'm not using a loop, so this always results in even
. I don't want a situation where I want to insert one row later, and then have to change the classes of all rows beneath it by hand. Am I just being petty? How would you cycle without being in a loop?
There's a section devoted to using cycle
outside of loops on the docs:
In some cases you might want to refer to the next value of a cycle from outside of a loop. To do this, just give the {% cycle %} tag a name, using "as", like this:
{% cycle 'row1' 'row2' as rowcolors %}
From then on, you can insert the current value of the cycle wherever you'd like in your template by referencing the cycle name as a context variable. If you want to move the cycle onto the next value, you use the cycle tag again, using the name of the variable. So, the following template:
<tr> <td class="{% cycle 'row1' 'row2' as rowcolors %}">...</td> <td class="{{ rowcolors }}">...</td> </tr> <tr> <td class="{% cycle rowcolors %}">...</td> <td class="{{ rowcolors }}">...</td> </tr>
would output:
<tr> <td class="row1">...</td> <td class="row1">...</td> </tr> <tr> <td class="row2">...</td> <td class="row2">...</td> </tr>
So in your case, you'd just declare it once and then call {% cycle name %}
on every row.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With