Henrik speaking at a conference

Hi, I’m Henrik Joreteg

Mobile web consultant, developer, and speaker

posts | twitter | email | hire | book | my startup: Xchart.com

The Djangonauts thought of everything: {% for %} tag, reversed

I can’t tell you how often I’ve hit a snag while building something in Django, only to find out that a solution to my problem is already part of the framework. Here’s one such example:

I’m passing a list of “Program” objects to the template and need to loop through them in the template. In a single request I’m outputting a fairly complex html file that I’m using to display multiple “pages” within a jQTouch app. That may sound strange unless your familiar with jQTouch. You see, the thing is, I want to do as few server requests as possible since having to use the iPhone’s data connection takes away from the super fast “native” feel that you can achieve with a pre-loaded app in jQTouch.

The reason is irrelevant, but in one part of the template I need this list sorted in descending order, and in another part of the same template I want to loop through the same list in ascending order. Obviously passing the same list twice in different orders seems unnecessary.

After some digging, I realized all I have to do is tack-on a “reversed” argument to the “for” tag.

    {% for program in programs reversed %}
    <li>{{ program.name }}</li>
    {% endfor %}

Problem solved. So sweet… I <3 Django!