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
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...
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With