How to use dicts in Mako templates?

ぐ巨炮叔叔 提交于 2019-12-01 11:23:18
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)

Pass dict1 to to_bunch function before passing it to Mako template. Unfortunately Mako doesn't provide any hooks to do this automatically.

Simplification of Łukasz' example:

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!