djangodjango-templatesdjango-template-filters

How to declare a variable and increment it in Django templates


How to initialize a numerical variable in Django templates.

{% with i=1 %}
    {% for cont in data %}

    {% if i|divisibleby:3 %}
         {{ forloop.i }}
    <!-- HTML -->

    {% elif i|divisibleby:2 %}
         {{ forloop.i }}
    <!-- HTML -->

    {% else %}
         {{ forloop.i }}
    <!-- HTML -->

    {% endif %}
   {% endfor %}

Getting this error due to {% with i=1 %}

TemplateSyntaxError at /tools-dash/

Unclosed tag on line 21: 'with'. Looking for one of: endwith.

The variable i is not being incremented by each {{ forloop.i }}. For each row in DB I get the same template in else part. How this can be changed to alternative ones.


Solution

  • There's no need to create a new variable. You can use your normal for loop, and check if forloop.counter is divisible by 3 or 2. Like so:

    {% for cont in data %}
    
        {% if forloop.counter|divisibleby:3 %}
            {{ forloop.counter }}
            <!-- HTML -->
    
        {% elif forloop.counter|divisibleby:2 %}
            {{ forloop.counter }}
            <!-- HTML -->
    
        {% else %}
            {{ forloop.counter }}
            <!-- HTML -->
    
        {% endif %}
    
    {% endfor %}