Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over object in Jinja2?

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

like image 295
Dan Avatar asked Jun 06 '12 19:06

Dan


2 Answers

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...

like image 103
Metal3d Avatar answered Nov 04 '22 15:11

Metal3d


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 %}
like image 4
fceruti Avatar answered Nov 04 '22 16:11

fceruti