Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mustache usage example
I have put together a this gist with my example code of usage of Mustache, I found the examples online a bit simplistic (for example both template and data were passed to Mustache.render inline) so maybe somebody else will be able to reuse it.
It also is the code for my article "2 things I did not understand about Mustache.js" http://morenafiore.com/2-things-i-did…about-mustache/
{
"panels": [
{
"id": "5",
"title": "Panel 5",
"desc": "Description 5",
"links": [
{
"url": "url1",
"title": "link1"
},
{
"url": "url2",
"title": "link2"
},
{
"url": "url3",
"title": "link3"
}
]
},
{
"id": "6",
"title": "Panel 6",
"desc": "Description 6",
"links": [
{
"url": "url1",
"title": "link1"
},
{
"url": "url2",
"title": "link2"
},
{
"url": "url3",
"title": "link3"
}
]
},
{
"id": "7",
"title": "Panel 7",
"desc": "Description 7",
"links": [
{
"url": "url1",
"title": "link1"
},
{
"url": "url2",
"title": "link2"
},
{
"url": "url3",
"title": "link3"
}
]
},
{
"id": "8",
"title": "Panel 8",
"desc": "Description 8",
"links": [
{
"url": "url1",
"title": "link1"
},
{
"url": "url2",
"title": "link2"
},
{
"url": "url3",
"title": "link3"
}
]
},
{
"id": "9",
"title": "Panel 9",
"desc": "Description 9",
"links": [
{
"url": "url1",
"title": "link1"
},
{
"url": "url2",
"title": "link2"
},
{
"url": "url3",
"title": "link3"
}
]
}
]
}
<!DOCTYPE html>
<html>
<head>
<title>Mustache</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.1.0/mustache.min.js"></script>
</head>
<body>
<div class="container">
</div>
<script type="text/javascript">
$(document).ready(function(){
$.when($.ajax({url: "../data/template.mst", dataType: 'text'}),$.ajax({url: "../data/test.json"}))
.done(function(template, data){
Mustache.parse(template[0]);
var rendered = Mustache.render(template[0], {panels: data[0].panels});
$(".container").html(rendered);
})
.fail(function(){
alert("Sorry there was an error.");
});
});
</script>
</body>
</html>
{{#panels}}
<div class="resultItem">
<h3 class="title">{{title}}</h3>
<p class="desc">{{desc}}</p>
<ul class="links">
{{#links}}
<li><a href="{{url}}">{{title}}</a></li>
{{/links}}
</ul>
</div>
{{/panels}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment