我试图用Mustace来渲染复杂的对象。我实际上在Python中使用pystache,但文档说它与Mustache的JS版本兼容。
在胡子,一切都很好,如果
information
是一个简单的字符串:
{{information}}
Mustache渲染的值
信息
像
XYZPDQ
例如
如果
信息
是一个复杂的对象,但它不起作用:
{{information.property1}} - {{information.property2}}
没有显示任何内容。
我希望看到这样的事情:
I am property 1 - XYZPDQ
还有部分。但这似乎是一种疯狂的过度杀戮。在这种情况下,我想会有这样的设置:
布局.html
<div>
{{> information}}
</div>
信息.mustache
{{property1}} - {{property2}}
现在,我将为每一处房产提供大量的八字胡偏好。这不可能是对的。
更新
:下面是@trvrm使用对象的答案的变体,显示了问题所在。它适用于字典,但不适用于复杂类型。如何处理复杂类型?
import pystache
template = u'''
{{greeting}}
Property 1 is {{information.property1}}
Property 2 is {{information.property2}}
'''
class Struct:
pass
root = Struct()
child = Struct()
setattr(child, "property1", "Bob")
setattr(child, "property2", 42)
setattr(root, "information", child)
setattr(root, "greeting", "Hello")
context = root
print pystache.render(template, context)
产量:
Property 1 is
Property 2 is
如果将最后两行更改为:
context = root.__dict__
print pystache.render(template, context)
然后你得到这个:
Hello
Property 1 is
Property 2 is
这个例子,再加上下面trvrm的回答,表明pystache似乎更喜欢字典,并且在处理复杂类型时遇到了麻烦。