如何在Mako模板中使用字典?

2 投票
2 回答
6110 浏览
提问于 2025-04-15 19:50

每当我把一个复杂的数据结构传给Mako时,处理起来就很麻烦。比如,我传了一个字典里面又有字典,里面还有列表,要在Mako中访问这些数据,我得这样写:

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

我在想,Mako有没有什么方法可以用简单的点号.来代替方括号[]来访问字典里的元素呢?

这样我就可以把上面的代码写成:

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

这样看起来就舒服多了,对吧?

谢谢,Boda Cydo。

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/

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)

在把dict1传给Mako模板之前,先把它传给to_bunch函数。可惜的是,Mako没有提供任何自动执行这个操作的方式。

撰写回答