开发者

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

开发者 https://www.devze.com 2023-03-17 07:49 出处:网络
I have this code {% for o in some_list %} Now I want to do some stuff if I am on an even line. Ho开发者_StackOverflow社区w can I do that?https://docs.djangoproject.com/en/dev/ref/templates/builtins

I have this code

{% for o in some_list %}

Now I want to do some stuff if I am on an even line. Ho开发者_StackOverflow社区w can I do that?


https://docs.djangoproject.com/en/dev/ref/templates/builtins/#divisibleby

{% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}


In first level cycle:

{% cycle 'odd' 'even' %}

Reference:

  • Documentation for cycle template tag


<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>


<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

精彩评论

暂无评论...
验证码 换一张
取 消