On Tue, May 18, 2010 at 12:46 AM, Barry <barrydan...@comcast.net> wrote: > Hi-- > > I want to dynamically display the contents of results (an array of > dictionaries with the same keys) as a table where the column headers > are a select group of keys in the variable result_col_titles and the > order of the columns is the same as the order of the keys in > result_col_titles. I imagine the template code would be something like > what is below but I don't know how to reference a dictionary item > value when the key value is in a variable and not hard-coded in the > template. > > This seems pretty basic but I didn't see it in the Definitive Guide > to Django. > > Thanks > > Barry > =========================================================================== > <table> > <tr> > {% for title in result_col_titles %} > <th> > {{ title }} > </th> > {% endfor %} > </tr> > {% for dictionary in result %} > <tr> > {% for title in result_col_titles %} > <td> > {{ dictionary.title }} > {{ dictionary.{{title}} }} > </td> > {% endfor %} > </tr> > {% endfor %} > </table> >
It's considered 'poor form' by django devs - too much work in the template. If you want the data in that order, arrange it so in the view. If you don't agree, add this 5 line template tag: from django import template register = template.Library() @register.filter def dict_get(hash, key): return hash[key] It should go in <some_app>/templatetags/dict_get.py You can then do: {% load dict_get %} {% for dict in list_of_dicts %} <tr> {% for title in titles %} <td>{{ dict|dict_get:title }}</td> {% endfor %} </tr> {% endfor %} Cheers Tom Hope that helps. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.