Saturday, July 18, 2009

Iterating over arrays in Django Templates for Google App Engine

This is a quick post to help anyone else who might be confused about how to iterate over arrays within Django Templates for Google App Engine.

Django templates are great. I am still exploring a lot of the flexibility they allow. One of the mundane features of the templating engine is the ability to iterate over data structures such as lists and arrays. This is fundamental to any web page showing a data table, list, data driven navigation or any similiar display. The great thing about Django templates is that this has a natural and familiar syntax. For a list, you write something along the lines of:


{% for item in list %}
Displaying or doing something with an item: {{ item }}
{% endfor %}


This iterates across all of the members in the list sequence, repeating the static text and item value for each item's value. Simple.

What about a dictionary? A dictionary is different from a list in many ways, but from the point of view of presenting data from a dictionary one of the key differences is that as you iterate you frequently want both the key and the value.

I faced this recently when beginning coding on my Google App Engine application and found the Django 0.96 template documentation Google Code refers to lacking an example of how iterating across a dictionary within the template is performed.

I found this post which succinctly demonstrated the modern Django Template syntax:


{% for key,value in dictionary.items %}
{{key}} is the key for the value {{ value }}
{% endfor %}



This was pretty intuitive and made sense. Unfortunately it does not work in Google App Engine. Why? Google App Engine still uses Django templates from Django 0.96, and this is one of the features added in the 1.0 release.

For those of us wanting to iterate over dictionaries in Google App Engine we need to use this somewhat less pretty but still functional format available in 0.96:


{% for item in dictionary.items %}
{{ item.0 }} is the key for value {{ item.1 }}
{% endfor %}


I can see why the Django folks improved the syntax.

Anyway, thanks go to Dan Ellis on this thread of the Django Google Group for pointing this out.

No comments:

Post a Comment