如何在Django模板中初始化变量并增加它?

时间:2015-05-08 05:01:00

标签: django django-templates

我正在尝试初始化变量并在for循环中递增它但是我收到以下错误:

无效的块标记:'set',预期'无空间'

这是我的代码:

<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>

1 个答案:

答案 0 :(得分:8)

你不需要。 Django已经附带forloop.counterforloop.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>