2

每当我将复杂的数据结构传递给 Mako 时,都很难对其进行迭代。例如,我传递一个 dict of list,并在 Mako 中访问它,我必须执行以下操作:

% for item in dict1['dict2']['list']: ... %endfor

我想知道 Mako 是否有一些机制可以[]用 simple 代替访问字典元素的用法.

然后我可以将上面的行写为:

% for item in dict1.dict2.list: ... %endfor

哪个更好,不是吗?

谢谢,博达赛多。

4

2 回答 2

8

Łukasz 示例的简化:

class Bunch:
    def __init__(self, d):
        for k, v in d.items():
            if isinstance(v, dict):
                v = Bunch(v)
            self.__dict__[k] = v

print Bunch({'a':1, 'b':{'foo':2}}).b.foo

另见: http ://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/

于 2010-02-28T19:56:20.980 回答
3
class Bunch(dict):
    def __init__(self, d):
        dict.__init__(self, d)
        self.__dict__.update(d)

def to_bunch(d):
    r = {}
    for k, v in d.items():
        if isinstance(v, dict):
            v = to_bunch(v)
        r[k] = v
    return Bunch(r)

在将dict1to_bunch传递给 Mako 模板之前将其传递给函数。不幸的是,Mako 没有提供任何钩子来自动执行此操作。

于 2010-02-28T19:28:01.797 回答