Template Variables as Indexes

1 view
Skip to first unread message

NewSpire

unread,
Apr 24, 2009, 12:18:15 PM4/24/09
to Django users
I have a list of forms, all of the same type, where I would like to
list each form side by side with the fields listed vertically. The
root of the problem is that I need to use a template variable as an
index on another template variable. Something like this.

<table>
{% for field in forms.0 %}
<tr>
<td>{{ field.label }}:</td>
{% for form in forms %}
<td>{{ form.field.{{ forloop.parentloop.counter0 }} }}</td>
{% endfor %}
</tr>
{% endfor %}
<table>

The outer loop if looping over form.0 to create a row for each set of
fields and the labels. The inner loop is providing the list of fields
for each row. Does anybody see a way to do something like this?

Thanks!
Andy

Doug B

unread,
Apr 24, 2009, 7:37:33 PM4/24/09
to Django users
Might not be the easiest way, but you could use a custom filter:

def formsbyfield(forms,field):
""" Given a list of similar forms, and a field name,
return a list of formfields, one from each form.
"""
return [form.fields.get(field,'') for form in forms]
register.filter('formsbyfield',formsbyfield)

{% for fieldname in forms.0.fields.keys %}
<tr>
{% for ff in forms|formsbyfield:fieldname %}
<td>{{ff}}</td>
{% endfor %}
</tr>
{% endfor %}

Something like that should work, though I haven't tested it.
Reply all
Reply to author
Forward
0 new messages