Django templates: forloop.first and forloop.last


Question

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?

1
43
6/25/2014 12:43:58 PM

Accepted Answer

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
32
8/24/2016 2:00:14 PM

couldn't you just use an "or" tag like {% if forloop.last or friendlist.count == 1 %}

            {% for f in friendslist %}

                    {% if forloop.first %}
                        // display something                            
                    {% endif %}

                    // display stuff

                    {% if forloop.last or friendlist.count == 1 %}
                        // display something
                    {% endif %}

            {% endfor %}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon