averageman
averageman

Reputation: 923

Django Templates: how flexible are variables?

I need to have a variable in a teplate that is basically a counter for a for-loop. The problem is: I need to manipulate it, depending on the for-element I am dealing with, I will have to reset the counter (an IF inside the for-loop).

Is this doable inside a Django template?

This is basically what I would like:

{% i = 0 %}
{% for l in list %}
    {% if i == 5 %}
        {% i = 0 %}
        Do Something
        <br>
    {% else %}
        {% i = i + 1 %}
    {% endif %}
{% endfor %}

Upvotes: 0

Views: 136

Answers (2)

Adri&#225;n
Adri&#225;n

Reputation: 6255

You can't with the builtin tags:

http://www.mail-archive.com/[email protected]/msg27399.html

The following snippets might be a good starting point:

EDIT: For the record, OP needed a conditional with divisibleby. See the accepted answer here plus the comments in this answer.

Upvotes: 1

Daniel Rosenthal
Daniel Rosenthal

Reputation: 1386

What you want is the forloop.counter variable that Django's template language provides.

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

You would do something like:

{% for element in list %}
    {% if forloop.counter > 5 %}
        Do something
    {% else %}
        Do something else
    {% endif %}
{% endfor %}

If you want to do something cyclically, you're basically doing a modulo operator (http://en.wikipedia.org/wiki/Modulo_operation), unfortunately, Django Template doesn't quite have this, but it does allow a 'divisible by' operator.

https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#divisibleby

So you'll add:

{% if {{ forloop.counter|divisibleby:"5" }} %}
    {{ whatever }}
{% endif %}

Upvotes: 1

Related Questions