Stephanie Neely
Stephanie Neely

Reputation: 73

Django second to last iteration of for loop

tabbed_fieldset.html states:

    if forloop.counter0 > 0 and forloop.last
           #do stuff`

I just wrote in a separate file:

for fieldset in adminform
    if not forloop.last
        include "admin/includes/tabbed_fieldset.html"
    else
         include "admin/includes/geo_fieldset.html"
     endif 
 endfor

So now tabbed_fieldset.html's code won't work anymore because if it is forloop.last, it wouldn't even be in tabbed_fieldset.html, it would be in geo_fieldset.html.

Is there a simple way to change forloop.last into forloop second to last?

Upvotes: 3

Views: 2962

Answers (1)

The Brofessor
The Brofessor

Reputation: 1048

Thanks for the code! Check out this website: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/

The for loop sets a number of variables available within the loop:

forloop.counter - The current iteration of the loop (1-indexed)

forloop.counter0 - The current iteration of the loop (0-indexed)

forloop.revcounter - The number of iterations from the end of the loop (1-indexed)

forloop.revcounter0 - The number of iterations from the end of the loop (0-indexed)

forloop.first - True if this is the first time through the loop

forloop.last - True if this is the last time through the loop

forloop.parentloop - For nested loops, this is the loop surrounding the current one

Basically, you would use forloop.revcounter or forloop.revcounter0

for fieldset in adminform
    if forloop.revcounter0 > 1
        include "admin/includes/tabbed_fieldset.html"
    else
        include "admin/includes/geo_fieldset.html"
    endif
endfor

Upvotes: 8

Related Questions