How to use dicts in Mako templates?

后端 未结 2 748
情书的邮戳
情书的邮戳 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:15

    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.

提交回复
热议问题