Reputation: 6553
I'm using Jinja2 on Google App Engine. I have a ListView which renders a generic template. At the moment, I'm not sure exactly what I want to display, so I just want to display each attribute of the model.
Is there a way to iterate over the object to output each one in a table cell?
For example:
{% for record in records %}
<tr>
{% for attribute in record %}
<td>{{ attribute }}</td>
{% endfor %}
</tr>
{% endfor %}
Any advice appreciated. Thanks
Upvotes: 13
Views: 13134
Reputation: 2941
Set getattr
in context is a bad idea (and there is already the built-in filter attr
). Jinja2 provides dict like access to properties.
I guess you should do:
{% for record in records %}
<tr>
{% for attribute in record.properties() %}
<td>{{ record[attribute] }}</td>
{% endfor %}
</tr>
{% endfor %}
This is better...
Upvotes: 29
Reputation: 2445
This will do the trick in simple python code:
for attribute in record.properties():
print '%s: %s' % (attribute, getattr(record, attribute))
You can put the getattr function in the context so you can call it in jinja2 as shown below:
{% for record in records %}
<tr>
{% for attribute in record.properties() %}
<td>{{ getattr(record, attribute) }}</td>
{% endfor %}
</tr>
{% endfor %}
Upvotes: 4