如何将列表转换为Flask模板的类对象

时间:2014-10-11 03:18:55

标签: python class loops flask jinja2

如何将列表列表转换为可以为foo.bar.spam等每个对象调用的类?

列表清单:

information =[['BlueLake1','MO','North','98812'], ['BlueLake2','TX','West','65343'], ['BlueLake3','NY','sales','87645'],['RedLake1','NY','sales','58923'],['RedLake2','NY','sales','12644'],['RedLake3','KY','sales','32642']]

这将是在Flask中使用jinja2模板为非常大的html表创建变量。

我希望能够做到这样的事情:

{% for x in information %}
    <tr>
        <td>{{x.name}}</td>
        <td>Via: {{x.location}} | Loop: {{x.region}}</td>
        <td>{{x.idcode}}</td>
    </tr>
{% endfor %}

还有其他用途,然后只有这个信息的这个模板,因此我希望它是一个可在其他地方使用的可调用类。

2 个答案:

答案 0 :(得分:3)

使用collections.namedtuple

>>> from collections import namedtuple
>>> Info = namedtuple('Info', ['name', 'location', 'region', 'idcode'])
>>>
>>> information =[
...     ['BlueLake1','MO','North','98812'],
...     ['BlueLake2','TX','West','65343'],
...     ['BlueLake3','NY','sales','87645'],
...     ['RedLake1','NY','sales','58923'],
...     ['RedLake2','NY','sales','12644'],
...     ['RedLake3','KY','sales','32642']
... ]
>>> [Info(*x) for x in information]
[Info(name='BlueLake1', location='MO', region='North', idcode='98812'),
 Info(name='BlueLake2', location='TX', region='West', idcode='65343'),
 Info(name='BlueLake3', location='NY', region='sales', idcode='87645'),
 Info(name='RedLake1', location='NY', region='sales', idcode='58923'),
 Info(name='RedLake2', location='NY', region='sales', idcode='12644'),
 Info(name='RedLake3', location='KY', region='sales', idcode='32642')]

答案 1 :(得分:1)

可能最常见的方法是将每个记录放入一个字典

info = []
for r in information:
    record = dict(name=r[0], location=r[1], region=r[2], idcode=r[3])
    info.append(record)

然后,Jinja2允许您使用x.name等访问属性,就像您在示例中一样。

{% for x in info %}
    <tr>
        <td>{{x.name}}</td>
        <td>Via: {{x.location}} | Loop: {{x.region}}</td>
        <td>{{x.idcode}}</td>
     </tr>
{% endfor %}

注意这种索引数据(x.name)的方式是一个jinja2特定的快捷方式(尽管它是从django模板中偷来的,它可能从其他东西中偷走了它。)

在python本身中你必须这样做:

for x in info:
    print(x['name'])
    # x.name will throw an error since name isn't an 'attribute' within x
    # x['name'] works because 'name' is a 'key' that we added to the dict