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