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

发布于 2024-08-23 10:03:11 字数 352 浏览 5 评论 0原文

每当我将复杂的数据结构传递给 Mako 时,就很难对其进行迭代。例如,我传递了列表的字典的字典,要在 Mako 中访问它,我必须执行以下操作:

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

我想知道 Mako 是否有某种机制可以替代 [] 用法,用简单的 . 访问字典元素?

然后我可以将上面的行写为:

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

哪个更好,不是吗?

谢谢,博达·西多。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凑诗 2024-08-30 10:03:11

Ł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/

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/

不气馁 2024-08-30 10:03:11
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 没有提供任何钩子来自动执行此操作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文