Content-dependent templates/partials with moustache.js
I'd like to use mous开发者_如何学Ctache.js to render the following JSON structure:
[
{type:'img', src:'some_url'},
{type:'text', text:'lorem ipsum ...'},
{type:'link', href:'some_url', label:'click here'},
// more entries ...
]
I'd like to render each item depending on type: img should br rendered as <img src="{{src}}">
, text as <p>{{text}}</p>
, etc. Is that possible with moustache.js or should I roll my own templating system? If it's possible, how would the template look like and how must I extend the JSON structure that it works as a moustache view?
Yes that's absolutely possible.
You could do something like
{{#myarray}} {{! loop through array}}
{{#src}} {{! if you have src it must be an img}}
<img src="{{src}}">
{{/src}}
{{#text}} {{! if you have text is must be a paragraph}}
<p>{{text}}{{/p}}
{{/text}}
{{#href}}} {{! if you have an href is must be an anchor}}
<a href="{{href}}">{{label}}</a>
{{/href}}
{{/myarray}}
No reason to extend the json at all, as long as the fields are unique to a certain type of output. You can just check if the field exists, and then if it does it must be output in a certain way.
The other thing you can do instead of having a 'type' field is have the json set with various flags to base you're template on (e.g. 'is_image: true', 'is_anchor: true', etc).
精彩评论