也许这是一个没有问题的问题,但是当您不在循环中时,如何使用 Django {% Cycle %}
功能或类似的功能?具体来说,我有一个手写的 HTML 表,因为它不是您需要在循环中执行的操作。我希望行交替,如下所示:
<tr class="{% cycle 'even' 'odd'%}"></tr>
<tr class="{% cycle 'even' 'odd'%}"></tr>
<tr class="{% cycle 'even' 'odd'%}"></tr>
但是我没有使用循环,所以这总是会产生even
。我不希望出现这样的情况:我想稍后插入一行,然后必须手动更改其下方所有行的类。我只是小气吗?您将如何在不循环的情况下循环?
最佳答案
有一节专门讨论在 the docs 上的循环之外使用 cycle
:
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>
因此,在您的情况下,您只需声明一次,然后在每一行调用 {% Cycle name %}
。
关于Django 模板循环交替行 - 无循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5820121/