我正在尝试使用 Mustache 渲染复杂的对象。我实际上在 Python 中使用 pystache,但文档说它与 Mustache 的 JS 版本兼容。
在 mustache 中,如果 information
是一个简单的字符串,一切都很好:{{information}}
例如,Mustache 将 information
的值呈现为 XYZPDQ
。
如果 information
是一个复杂的对象,它就不起作用:{{information.property1}} - {{information.property2}}
什么都不显示。
我期待看到这样的东西:我是属性 1 - XYZPDQ
还有偏音。但这似乎是一种疯狂的矫枉过正。在那种情况下,我想会有这样的设置:
布局.html
<div>
{{> information}}
</div>
信息. mustache
{{property1}} - {{property2}}
现在,我将为每个属性提供大量的 .mustache 部分。那是不对的。
更新:下面是@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 似乎更喜欢字典并且在处理复杂类型时遇到麻烦。
最佳答案
Pystache 渲染嵌套对象没有问题。
import pystache
template = u'''
{{greeting}}
Property 1 is {{information.property1}}
Property 2 is {{information.property2}}
'''
context={
'greeting':'Hello',
'information':{
'property1':'bob',
'property2':42
}
}
print pystache.render(template,context)
产量:
Hello
Property 1 is bob
Property 2 is 42
更新
如果我们替换上面的例子可以工作
class Struct():
pass
与
class Struct(object):
pass
关于python - mustache /pystache : Rendering complex objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25827884/