July 23, 2009

Tuple unpacking in django templates

I was stuck for about an hour on getting the tuple unpacking in django templates right. If one has a list of tuples say

mylst = [(a, b, c), (x, y, z), (l, m, n)],

then the easiest way to unpack this list in the template file is as follows.
In my case I had a list of tuples which contained the URL, title, and summary of a document.

{\% for item in mylst \%}
{{ item.0 }} {{ item.1}} {{ item.2 }}
{\% endfor \%}

One need not follow complex steps as mentioned in http://stackoverflow.com/questions/271077/django-how-to-do-tuple-unpacking-in-a-template-for-loop.

5 comments:

Brandon said...

if every tuple in the list has 3 items you can do

{% for x,y,z in list %}
{{x}},{{y}},{{z}}
{% endfor %}

Brandon said...

the stack overflow op had a list of tuples which also contained tuples. hence the complexity of the solution.

Dan said...

Thanks to both Ashwin and Brandon for help with this now obvious solution. You've save me pulling out even more hair in frustration.

evan said...

thanks!

wish i'd found your post before that stackoverflow page..

maybe post your solution there?

cheers

Ashwin Rao said...

Yes I added this content on stackoverflow. Thanks for the suggesion.