代码之家  ›  专栏  ›  技术社区  ›  101010

胡子/pystache:渲染复杂对象

  •  4
  • 101010  · 技术社区  · 10 年前

    我试图用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似乎更喜欢字典,并且在处理复杂类型时遇到了麻烦。

    1 回复  |  直到 10 年前
        1
  •  8
  •   trvrm    10 年前

    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