Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 509
Neelabh Singh Avatar asked Jan 08 '23 10:01

Neelabh Singh


1 Answers

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>
like image 64
rnevius Avatar answered Jan 16 '23 20:01

rnevius