Django templates: forloop.first and forloop.last

Solution 1:

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

Solution 2:

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 %}