2017-04-10 92 views
0

我有我的模板下面的代码:如何获取django模板循环中第二,第三,第n遍的值?

{% with element=vals|first %} #can use last here to get the last value 
    {% for key,value in element.items %} 
     <td>{{ value.corr }}</td> 
     <td>{{ value.str }}</td> 
     <td>{{ value.sig }}</td> 
    {% endfor %} 
{% endwith %} 

这将使我在循环的第一次迭代的第一个值。

如何获得第二,第三和第n?

我想过使用切片,但这似乎并没有在这里工作 - 或者我没有正确格式化切片。

请帮忙!

编辑:我http://stardict.sourceforge.net/Dictionaries.php下载列表:

[{('age', 'after'): 
     {'str': 'one', 'sig': 'two', 'cor': 'three'} 
    }, 
{('age', 'before'): 
     {'str': 'zero', 'sig': 'one', 'cor': 'four'} 
    }, 
{('exp', 'after'): 
     {'str': 'one', 'sig': 'two', 'cor': 'three'} 
    }, 
{('exp', 'before'): 
     {'str': 'zero', 'sig': 'one', 'cor': 'four'} 
}] 

编辑2:所需的输出

<table class="table table-striped table-hover"> 
    <thead> 
     <tr> 
      <th>Parameters</th> 
      <th>Pos/Neg</th> 
      <th>Str</th> 
      <th>Sig</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <th scope="row">First Table Row</th> 
       {% with element=q3vals|first %} 
        {% for key,value in element.items %} 
         {% if forloop.counter == 1 %} 
          <td>{{ value.corr }}</td> 
          <td>{{ value.str }}</td> 
          <td>{{ value.sig }}</td> 
         {% endif %} 
        {% endfor %} 
       {% endwith %} 
     </tr> 
     <tr>#second loop through the list of dicts</tr> 
     <tr>#third loop through the list of dicts 
     <tr> 
      <th scope="row">Fourth Table Row</th> 
       {% with element=q3vals|last %} #last loop through 
        {% for key,value in element.items %} 
         <td>{{ value.corr }}</td> 
         <td>{{ value.str }}</td> 
         <td>{{ value.sig }}</td> 
        {% endfor %} 
       {% endwith %}  
     </tr> 
    </tbody> 
</table> 
+0

如果任何回答以下问题的帮助你,然后将其标记为接受的请。在StackOverflow中这是一个很好的做法:) –

回答

3

您可以使用forloop.counter

{% with element=vals|first %} {# can use last here to get the last value #} 
    {% for key,value in element.items %} 
     {% if forloop.counter == 2 %} {# or if forloop.first etc. #} 
      <td>{{ value.corr }}</td> 
      <td>{{ value.str }}</td> 
      <td>{{ value.sig }}</td> 
     {% endif %} 
    {% endfor %} 
{% endwith %} 

[编辑]:

{% for dict in q3vals %} 
    {% for key, inner_dict in dict.items %} 
    {# key, each time, will be ('age', 'after'), ('age', 'before') etC#} 
    {# inner_dict, each time, will be {'str': 'one', 'sig': 'two', 'cor': 'three'} etC#} 
     <tr> 
      <th scope="row">Table Row #{{ forloop.counter }}</th> 
      <td>{{ inner_dict.cor }}</td> 
      <td>{{ inner_dict.str }}</td> 
      <td>{{ inner_dict.sig }}</td> 
     </tr> 
    {% endfor %} 
{% endfor %} 
+0

由于它从零索引开始,所以它应该是'forloop.counter0'对吗? – Surajano

+0

编号'forloop.counter'从1开始。如果你想从0开始,那么使用'forloop.counter0'并且做'{%if forloop.counter0 == 1%}'(这将是第二个元素)。 –

+0

@nik_m必须做一些不正确的事情:我的清单列表看起来像我上面的编辑。 {%with .. | first%}语句为我提供了第一组值。但我不知道使用“with”语句来获得第二个过滤器的过滤器类型。 – Kickasstimus

相关问题