Django Template – Increment the value of a variable

Changing the state of an object in a Django template is discouraged. You should probably bite the bullet, calculate the condition beforehand and pass extra state to the template so you can simplify the template logic.

I’m no purist in this regard by the way, but I have been bitten by the purposeful limitations of Django templates a few times. You’re better off not fighting against it, in my opinion.

Being that your intention seems to be to filter out non-matching items, an alternative would be to filter out those in the view and then use {{ forloop.counter }} to sort out the link text you want. So in the view you have something like this:

new_lst = filter(lambda x: x.attr0 == attr0 and x.attr1 == attr1, lst)

And then, in your template:

{% for object in new_lst %}
   <li><a href="https://stackoverflow.com/questions/8659560/{{ object.get_absolute_url }}"> Link {{ forloop.counter }} </a></li>
{% endfor %}

Leave a Comment