Django Template:如何在嵌套for循环中使用父变量

时间:2014-05-22 23:28:13

标签: python django django-templates django-views

{% for round in rounds %}
  <div id="round_{{forloop.counter}}">
    {% for match in r{{forloop.counter}}_matches %}
        <p>I am match {{ match }}!</p>
        <p>I am one of the matches in round {{round}}!</p>
    {% endfor %}
  </div>
{% endfor %}

roundsr1_matches, r2_matches等是视图中定义的通向此模板的对象列表。

显然,这个片段在逻辑上显示了我想要发生的事情,但是由于显而易见的原因它不起作用。代替能够在第二个{{forloop.counter}}循环中使用for,我怎样才能加载仅属于当前轮次的匹配?

作为旁注,我还有一个传递给此模板的变量,此处未显示,名为matches,每个match对象都有一个名为round的字段,告诉你哪个回合所属的回合。我想我会在视图中做更多的逻辑,所以我有r1_matches, r2_matches等预先剪切到他们自己的列表中。重点是,如果做{% for match|"round={{forloop.counter}}" in matches %}这样的事情更有意义,我很乐意这样做,但是我仍然需要访问父循环的计数器,就像其他方式一样。

1 个答案:

答案 0 :(得分:1)

你应该做什么

context = {"rounds":[["match1","match2","match3"],["match2","match1"]]

{% for round in rounds %}
   <div id="round_{{forloop.counter0}}">
      {% for match in round %}
          I am match {{forloop.counter1}}
          in round {{forloop.counter0 }}
      {% endfor %}
   </div>
{% endfor %}

我认为这至少是正确的......

iirc counter0是最外面的forloop,counter1是下一个内部(我认为你可以到9)

counter指的是当前的

相关问题