我有桌子:
{% for item in items %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ item.field }}</td>
</tr>
{% for child in item.childs.all %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ child.field }}</td>
</tr>
{% endfor %}
{% endfor %}
但是第二个forloop.counter在第二个循环中从1开始计数。我想只为所有行获得一个计数器。怎么做?
答案 0 :(得分:3)
您可以write a custom template tag计算计数器(假设每行的列数相同):
@register.simple_tag
def abs_counter(row, col, col_total)
return return ((row - 1) * col_total) + col
和
{% for item in items %}
...
{% for child in items.children.all %}
{% abs_counter forloop.parentloop.counter forloop.counter items.children.all|length %}
{% endfor %}
{% endfor %}