如何在 Mako 模板中使用 dicts? [英] How to use dicts in Mako templates?
问题描述
每当我将复杂的数据结构传递给 Mako 时,都很难对其进行迭代.例如,我传递一个 dict of list 的 dict,要在 Mako 中访问它,我必须执行以下操作:
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
我想知道 Mako 是否有某种机制可以代替 []
用法来使用简单的 .
访问字典元素?
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
哪个更好,不是吗?
谢谢,博达·西多.
推荐答案
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 传递给 to_bunch
函数,然后再将其传递给 Mako 模板.不幸的是,Mako 没有提供任何钩子来自动执行此操作.
Pass dict1 to to_bunch
function before passing it to Mako template. Unfortunately Mako doesn't provide any hooks to do this automatically.
这篇关于如何在 Mako 模板中使用 dicts?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!