2015-04-20 20 views
1

我有表:如何为两个forloops设置一个计数器?

{% 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 %} 

但从1.第二循环内的第二forloop.counter计数我想只有一个所有行柜台。怎么做?

回答

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 %} 
相关问题