Django 模板循环交替行 - 无循环

标签 django django-templates

也许这是一个没有问题的问题,但是当您不在循环中时,如何使用 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/

相关文章:

python - celery 不工作 : Cannot connect to amqp://guest:**@127. 0.0.1:5672//

html - Django css 背景图像

python - Django应用程序的<str :slug> and <slug:slug> in urls. py的区别

django - 在开发环境中本地提供 django 媒体文件

Django:两个用户具有相同的用户名

python - 在 Django 模板中创建年份下拉列表

python - TemplateDoesNotExist at/polls/- 在 Django 教程中

django - 为什么在 settings.ALLOWED_INCLUDE_ROOTS 中使用变量不允许我使用 {% ssi %}?

jquery - 如何让 Django-Ajax-Selects 在 Django Admin 中工作?

python - Django REST Framework PATCH 在必填字段上失败