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?
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.
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'.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With