在Jinja2中迭代对象?

时间:2012-06-06 19:44:02

标签: google-app-engine jinja2

我在Google App Engine上使用Jinja2。我有一个ListView,它呈现一个通用模板。目前,我不确定我想要显示什么,所以我只想显示模型的每个属性。

有没有办法迭代对象以输出表格单元格中的每一个?

例如:

{% for record in records %}
<tr>
{% for attribute in record %}
<td>{{ attribute }}</td>
{% endfor %}
</tr>
{% endfor %}

任何建议表示赞赏。 感谢

2 个答案:

答案 0 :(得分:23)

在上下文中设置getattr是一个坏主意(并且已经有内置过滤器attr)。 Jinja2提供dict like访问属性的权限。

我想你应该这样做:

{% for record in records %}
    <tr>
    {% for attribute in record.properties() %}
        <td>{{ record[attribute] }}</td>
    {% endfor %}
    </tr>
{% endfor %}

这样更好......

答案 1 :(得分:3)

这将在简单的python代码中完成:

for attribute in record.properties():
    print '%s: %s' % (attribute, getattr(record, attribute))

您可以将 getattr 函数放在上下文中,以便在jinja2中调用它,如下所示:

{% for record in records %}
    <tr>
    {% for attribute in record.properties() %}
        <td>{{ getattr(record, attribute) }}</td>
    {% endfor %}
    </tr>
{% endfor %}