【问题标题】:How can I check for loop count? (and whether it is even or odd) [duplicate]如何检查循环计数? (以及它是偶数还是奇数)[重复]
【发布时间】:2014-02-12 17:47:21
【问题描述】:
{% for p in posts %}
   <div id="even">{{ p.title }}</div>
   <div id="odd">{{ p.title }}</div>
{% endfor %}

我需要创建这样的东西:

{% for p in posts %}
   {% if forloop_count is even %}
       <div id="even">{{ p.title }}</div>
   {% else %}
       <div id="odd">{{ p.title }}</div>
   {% endif %}
{% endfor %}

如何检查循环计数? (以及它是偶数还是奇数)

【问题讨论】:

标签: django


【解决方案1】:

这是您真正的基本要求,还是您只是想在两个 div 类之间循环?它们必须是奇数/偶数,还是只是交替出现?

{% for o in some_list %}
    <tr class="{% cycle 'row1' 'row2' %}">
        ...
    </tr>
{% endfor %}

参考:https://docs.djangoproject.com/en/dev/ref/templates/builtins/

在你的情况下是:

{% for p in posts %}
    <div id="{% cycle 'even' 'odd' %}">{{ p.title }}</div>
{% endif %}

【讨论】:

    【解决方案2】:

    使用divisableby

    {% for p in posts %}
       {% if forloop.counter|divisibleby:"2" %} {# is even #}
           <div id="even">{{ p.title }}</div>
       {% else %}
           <div id="odd">{{ p.title }}</div>
       {% endif %}
    {% endfor %}
    

    或者如果它只是一个 id 使用 cycle e.g.

    {% cycle 'odd' 'even' %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2011-11-12
      • 2010-09-14
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多