How to use dicts in Mako templates?

后端 未结 2 766
情书的邮戳
情书的邮戳 2021-01-15 16:55

Whenever I pass a complicated data structure to Mako, it\'s hard to iterate it. For example, I pass a dict of dict of list, and to access it in Mako, I have to do something

2条回答
  •  爱一瞬间的悲伤
    2021-01-15 17:19

    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/

提交回复
热议问题