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

gee*_*eks 4 django django-templates

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

无效的块标记:'set',预期'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>
Run Code Online (Sandbox Code Playgroud)

rne*_*ius 8

你不需要.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>
Run Code Online (Sandbox Code Playgroud)