Yin Yang
Yin Yang

Reputation: 1806

Django Template - Increasing the value of a variable in a template in a for loop

I need to display a rank against each item I'm looping over in a for loop in a Django template. I'm initially displaying 10 items on the page and loading 10 more items each time the load more button is pressed.

I tried using the {{ forloop.counter }} but that works only for the first 10 items. Since the call involves AJAX, each time new items are appended they have ranks from 1-10.

I can send a rank variable to the template, but I need a method that increments that rank variable by 1 each time in the for loop. Is there any default Django filter for this? Or can anyone help me write a custom filter for this?

Thanks.

Upvotes: 2

Views: 4739

Answers (3)

trnsnt
trnsnt

Reputation: 694

My idea will be to create a counter class that you will used to increment your rank

class Counter:
    counter = 0    
    def increment(self):
        self.counter += 1
        return self.counter
    def set_to_zero(self):
        self.counter = 0
        return self.counter

and pass it in the context. Then each times you are in your loop you can increment it with

{{ counter.increment }}

Upvotes: 2

Yin Yang
Yin Yang

Reputation: 1806

I ended up combing the {{ forloop.counter }} and the rank variable using the add filter.

{{ forloop.counter|add:rank }}

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 600059

If you have a rank integer already, you can simply use the existing add filter to add the counter:

{{ forloop.counter0|add:rank }}

Upvotes: 5

Related Questions