{% cycle %} work around for nested for loops?

爱⌒轻易说出口 提交于 2019-12-08 18:41:58

问题


I ran into an interesting "oversight" in the Django {% cycle %} template tag. This has been listed as a bug, but I'm wondering if there is a workaround for it?

{% for r1 in range_0_2 %}
  {% for r2 in range_0_3 %}
   {{ r1 }}-{{ r2 }}-{{ cycle 'even' 'odd' }}
  {% endfor %}
{% endfor %}

This yields:

0-0-even
0-1-odd
0-2-even
1-0-odd
1-1-even
1-2-odd

It should yield:

0-0-even
0-1-odd
0-2-even
1-0-even
1-1-odd
1-2-even

回答1:


I have noticed the same problem in my templates.

You can use a workaround like the following:

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



回答2:


I use "include" for inner loop content

{% regroup employee_bypos_list by pos as by_pos %}
{% for pos_set in by_pos %}
    <h2>«{{ pos_set.grouper.address }}»</h2>
    {% with pos_set.list as employee_list %}
        {% include 'website/employee/_staff_by_post.html' %}
    {% endwith %}
{% endfor %}


来源:https://stackoverflow.com/questions/2253050/cycle-work-around-for-nested-for-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!