Neelabh Singh
Neelabh Singh

Reputation: 2678

How to initialize the variable and increment it in Django template?

I am trying to initialize the variable and increment it in the for loop but I'm getting the following error:

Invalid block tag: 'set', expected 'endspaceless'

This is my code:

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

Upvotes: 4

Views: 5658

Answers (1)

rnevius
rnevius

Reputation: 27092

You don't need to. Django already comes with a forloop.counter, as well as a forloop.counter0. You can use it directly:

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

Upvotes: 10

Related Questions