I'm trying to wrap my head around rending complex objects using Mustache. I'm actually in Python using pystache, but the docs say it's compatible with the JS edition of Mustache.
In mustache, all works nice if information
were a simple string: {{information}}
Mustache renders the value of information
as XYZPDQ
for example.
If information
were a complex object however, it doesn't work: {{information.property1}} - {{information.property2}}
shows nothing.
I'm expecting to see something like this: I am property 1 - XYZPDQ
There's also partials. But that seems like a crazy amount of overkill. In that situation, I suppose there would be a setup like this:
layout.html
<div>
{{> information}}
</div>
information.mustache
{{property1}} - {{property2}}
Now, I will have an enormous number of .mustache partials around for every property. That can't be right.
UPDATE: Here's a variation of @trvrm's answer below using objects, which shows the problem. It works with dictionaries, but not complex types. How do we do this with complex types?
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)
yields:
Property 1 is
Property 2 is
If you change the last two lines to this:
context = root.__dict__
print pystache.render(template, context)
Then you get this:
Hello
Property 1 is
Property 2 is
That example, plus trvrm's answer below, shows that pystache seems to prefer dictionaries and has trouble with complex types.