2015-05-08 75 views
2

我想初始化变量并增加它在for循环,但我发现了以下错误:如何初始化变量并在Django模板中增加它?

无效块标记:“设置”,预计“endspaceless”

这是我的代码:

<tr{{ row.attr_string|safe }}> 
    {% spaceless %} 

     {% set counter = 0 %} 

     {% for cell in row %} 

      {% set counter= counter+1 %} 

      {% if counter < 4 %}     
       {% include "horizon/common/_data_grid_cell.html" %}   
      {% else %} 
       {% include "horizon/common/_data_table_cell.html" %} 
      {% endif %} 

     {% endfor %} 

    {% endspaceless %} 
</tr> 

回答

6

你不需要。 Django已经出现了forloop.counter以及forloop.counter0。您可以直接使用它:

<tr{{ row.attr_string|safe }}> 
    {% spaceless %} 

     {% for cell in row %} 

      {% if forloop.counter < 4 %}     
       {% include "horizon/common/_data_grid_cell.html" %}   
      {% else %} 
       {% include "horizon/common/_data_table_cell.html" %} 
      {% endif %} 

     {% endfor %} 

    {% endspaceless %} 
</tr> 
+0

谢谢,如果你发现我的问题是有用的,然后PLZ upvote它.. – geeks