views:

313

answers:

2

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 like:

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

I am wondering if Mako has some mechanism that could replace [] usage to access dictionary elements with simple .?

Then I could write the line above as:

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

Which is much nicer, isn't it?

Thanks, Boda Cydo.

+2  A: 
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.

Łukasz
Thank you Łukasz, this was an excellent answer and I understood everything.
bodacydo
+3  A: 

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/

Jesse Aldridge
Thank you Jesse. I am reading the document already! :) (I asked a similar question on another thread, and people suggested it. The thread is here, maybe you are also interested: http://stackoverflow.com/questions/2352181/how-to-use-a-dot-to-access-members-of-dictionary )
bodacydo
That is way better :)
Łukasz