RSS

Blog

Django: Two little but yet handy for loop tricks

h34 Sep 2009 –  Comments (3)

Comments

There's a typo in the forloop.first code. You never reference forloop.last

[] Paul ~ 6 months, 1 week ago at 12:55 p.m.

@Paul

Fixed it, thanks !

[] h3 ~ 6 months, 1 week ago at 3:04 p.m.

There are two problems with your first approach. If object_list is empty, then you'll get an empty UL tag (that is invalid). If object_list has just one element, then you will have to a LI with two class definitions (that is also invalid). To fix this, you would need to write such code:

{% for item in object_list %}
    {% if forloop.first %}<ul>{% endif %}
    <li>{% if forloop.first or forloop.last %} class="{% if forloop.first %}first{% else %}last{% endif %}"{% endif %}>
        {{ item }}
    </li>
    {% if forloop.last %}</ul>{% endif %}
{% endfor %}

[] Aidas Bendoraitis ~ 5 months, 3 weeks ago at 6:42 a.m.

Copyrighted stuff .. u know.