Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Template - Increment the value of a variable

I have the following code in my template

{% set counter = 0 %} {% for object in object_list %}     {% if object.attr1 == list1.attr1 and object.attr2 = list2.attr2 %}         <li><a href="{{ object.get_absolute_url }}"> Link {{counter++}} </a></li>      {% endif %} {% endfor %} 

I setting the value of a variable using this custom tag and what I want to do is to increment the value only if the if loop is satisfied. I know {{counter++}} does not work. But how can I write a custom tag that would do the same task?

like image 710
Sachin Avatar asked Dec 28 '11 18:12

Sachin


People also ask

What does {% %} mean in Django?

The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output. One can use various boolean operators with Django If Template tag.

Can you do math in Django template?

Use django-mathfilters. In addition to the built-in add filter, it provides filters to subtract, multiply, divide, and take the absolute value. For the specific example above, you would use {{ 100|sub:object.

When {% extends %} is used for inheriting a template?

extends tag is used for inheritance of templates in django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables.


1 Answers

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="{{ object.get_absolute_url }}"> Link {{ forloop.counter }} </a></li> {% endfor %} 
like image 104
Eduardo Ivanec Avatar answered Sep 28 '22 04:09

Eduardo Ivanec