VA splash
VA splash

Reputation: 573

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.

Upvotes: 1

Views: 978

Answers (2)

mahendra singh
mahendra singh

Reputation: 1

here you need to close django tage with like {% with i=1 %} ......your code {% endwith %}

Upvotes: 0

Greg Kaleka
Greg Kaleka

Reputation: 2000

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

Upvotes: 2

Related Questions