How do I get odd and even values in a Django for loop template?

后端 未结 4 786
耶瑟儿~
耶瑟儿~ 2020-12-01 04:21

I have this code

{% for o in some_list %}

Now I want to do some stuff if I am on an even line. How can I do that?

相关标签:
4条回答
  • 2020-12-01 04:38

    In first level cycle:

    {% cycle 'odd' 'even' %}
    

    Reference:

    • Documentation for cycle template tag
    0 讨论(0)
  • 2020-12-01 04:42
    <div class="row">
    {% for post in posts %}
          {% cycle 'odd' 'even' %}
          {% if cycle == 'odd' %}
            <div class="col-md-6">Odd posts</div>
          {% else %}
            <div class="col-md-6">Even posts</div>
          {% endif %}
        {% endfor %}
    </div>
    

    OR

    <div class="row">
    {% for post in posts %}
       {% if forloop.counter|divisibleby:2 %}
            <div class="col-md-6">Even posts</div>
          {% else %}
            <div class="col-md-6">Odd posts</div>
          {% endif %}
        {% endfor %}
    </div>
    
    0 讨论(0)
  • 2020-12-01 04:55
    <div class="row">
    {% for post in posts %}
       {% if loop.index is divisibleby 2 %}
            <div class="col-md-6">Even posts</div>
          {% else %}
            <div class="col-md-6">Odd posts</div>
          {% endif %}
        {% endfor %}
    </div>
    

    http://mitsuhiko.pocoo.org/jinja2docs/html/templates.html#id3

    0 讨论(0)
  • https://docs.djangoproject.com/en/dev/ref/templates/builtins/#divisibleby

    {% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}
    
    0 讨论(0)
提交回复
热议问题