python - mustache /pystache : Rendering complex objects

标签 python mustache pystache

我正在尝试使用 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/

相关文章:

python - 了解 pystache 中的 lambda

python - 在 mustache/pystache 中迭代字典的键和值

python - GeoDjango:无法导入名称 GEOSException 已修复,现在 [WinError 126]

python - 以编程方式逐行跟踪 Python 程序/语句的执行

javascript - 在 mustache JS 中填充和选择一个选择框

javascript - 发布复选框值

python - 通过python从终端更改目录地址

Python Popen - 环境 - ffmpeg 崩溃

jquery - 在 Mustache.js 模板中创建一个可用的 jQuery 按钮

python - Pystache 无需转义(未转义)