Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django templates: forloop.first and forloop.last

Tags:

python

django

I have the following code in my template:

{% for f in friendslist %}          {% if forloop.first %}             // display something                                     {% endif %}          // display stuff          {% if forloop.last %}             // display something         {% endif %}  {% endfor %} 

It works as expected when there is more than one item in the friendslist. But if there is just 1 item, then the content inside the forloop.last conditional does not display.

I guess this is because the loop in that case is the first, but I mean it's also the last right? So why dosn't both contents inside first and last conditional show?

like image 604
Sammy Avatar asked Aug 09 '11 15:08

Sammy


People also ask

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.

What does the Django template filter pluralize do?

In Sendwithus you can use the pluralize filter to change the suffix of a word. Like Django's pluralize filter it returns a plural suffix if the first argument is an integer greater than 1 or a sequence with more than 1 item. If a plural suffix isn't specified pluralize defaults to 's'.

How do you break a loop in Django?

There is no break in Django template system but you can achieve an statement like break with bellow architecture. (Loop will go iteration but u don't do anything.) 1- Use with to define a variable to determine current status, 2- Use a template custom tag to change statement to negate current status.


1 Answers

In my code they both execute if there is only one element in friendslist. Here is a test you can run in the shell where maybe you can figure out what isn't working:

$ ./manage.py shell  >>> from django import template >>> t = template.Template("""{% for f in friendslist %}                          {% if forloop.first %}                              First of the loop                                                      {% endif %}                          {{ f }}                          {% if forloop.last %}                              Last of the loop                          {% endif %}                  {% endfor %}""")  >>> c = template.Context({'friendslist' : ['one element',]}) >>> t.render(c)                           First of the loop                      one element                           Last of the loop 
like image 141
newmaniese Avatar answered Oct 02 '22 12:10

newmaniese