I am new to Mustache and I have a question in regard to converting script file to template correctly.
Assume that I have the following file
<script type="text/template" id="template-member-list-item">
{{#item_data}}
<tr id="{{user_login}}">
</tr>
{{/item_data}}
</script>
to get this file into html correctly, can I go like this?
var template = jQuery(above.html)[0].innerHTML;
var html = Mustache.to_html(template, JSON file);
jQuery('#content').append(html);
would this be correct?
<script type="text/javascript" src="http://zeptojs.com/zepto.min.js" ></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.js" ></script>
<div id="content"></div>
<script type="text/template" id="template-member-list-item">
{{#item_data}}
<tr id="name">
{{user_login}}
</tr>
{{/item_data}}
</script>
<script type="text/javascript">
$(function(){
var tpl = $("#template-member-list-item").html()
var html=Mustache.render(tpl,{item_data:{user_login:"test_user"}})
$("#content").html(html)
})
</script>
This is call Enumerable Section with Objects We always use below section to iterate collection in Mustache {{#}} {{/}}
Html will remain same
<script type="text/template" id="template-member-list-item">
{{#item_data}}
<tr id="{{user_login}}">
</tr>
{{/item_data}}
</script>
JSON input will be look like
var data = {
item_data: [
{ user_login: "Christophe"},
{ user_login: "John"}
]};
Here is rendering of html template
var template = $("#template-member-list-item").html();
var html = Mustache.to_html(template, data);
$('#content').html(html);
For more detail example see below link http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.