Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python mustache/pystache:渲染复杂对象_Python_Mustache_Pystache - Fatal编程技术网

Python mustache/pystache:渲染复杂对象

Python mustache/pystache:渲染复杂对象,python,mustache,pystache,Python,Mustache,Pystache,我正试着用小胡子画复杂的物体。实际上,我在Python中使用pystache,但文档说它与JS版的Mustache兼容 在mustache中,如果信息是一个简单的字符串:{{{information} 例如,Mustach将信息的值呈现为XYZPDQ 如果information是一个复杂的对象,那么它就不起作用:{{information.property1}}-{{information.property2}什么也不显示 我希望看到这样的情况:I am property 1-XYZPDQ 还有

我正试着用小胡子画复杂的物体。实际上,我在Python中使用pystache,但文档说它与JS版的Mustache兼容

在mustache中,如果
信息
是一个简单的字符串:
{{{information}

例如,Mustach将
信息的值呈现为
XYZPDQ

如果
information
是一个复杂的对象,那么它就不起作用:
{{information.property1}}-{{information.property2}
什么也不显示

我希望看到这样的情况:
I am property 1-XYZPDQ

还有偏音。但这似乎是一种疯狂的过度杀伤力。在这种情况下,我想会有这样的设置:

layout.html

<div>
    {{> information}}
</div>
现在,我将有一个巨大的数量。胡子左右的每一个属性的部分。那不可能是对的

更新:下面是@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 
Hello
  Property 1 is bob
  Property 2 is 42
如果将最后两行更改为:

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)
收益率:

   Property 1 is 
   Property 2 is 
Hello
  Property 1 is bob
  Property 2 is 42
更新

如果我们更换

class Struct():
    pass


我想你在pystache发现了一只虫子。从代码中我可以看出,这应该是可行的,但是如果您查看中的源代码,我认为存在逻辑错误。第53行以后的代码应该在您传入的结构上执行,但是没有。谢谢您的帮助。我打开了一个问题:在github问题上添加了一些注释:如果用
class Struct(object)
替换
class Struct()
,代码似乎确实可以工作。我不知道如何在
context.py中修复测试,谢谢@trvrm的帮助。