<h1>{{title}}</h1>
<ul>
{{#names}}
<li>{{name}}</li>
{{/names}}
</ul>
var data = {
"title": "Story",
"names": [
{"name": "Tarzan"},
{"name": "Jane"}
]
}
<h1>Story</h1> <ul> <li>Tarzan</li>
<li>Jane</li> </ul>
<html> <body onload="loadUser"> <div id="target">Loading...</div> <script id="template" type="x-tmpl-mustache"> Hello {{ name }}! </script> </body> </html>
function loadUser() { var template = $('#template').html(); Mustache.parse(template); // optional, speeds up future uses var rendered = Mustache.render(template, {name: "Luke"}); $('#target').html(rendered); }
View:
{ "name": "Chris", "company": "<b>GitHub</b>", "address": { city: "Pune", state: "Mah" } }
Template:
{{name}}
{{age}}
{{company}}
{{{company}}}
{{&company}}
{{address.city}}
Output:
Chris <b>GitHub</b> <b>GitHub</b> <b>GitHub</b> Pune
Sections:
- Nothing but loop
False Values or Empty Lists
- null, undefined, false, 0, or NaN, or is an empty string or an empty list, the block will not be rendered
View:
{ "stooges": [ { "name": "Moe" }, { "name": "Larry" }, { "name": "Curly" } ] }
Template:
{{#stooges}} <b>{{name}}</b> {{/stooges}}
Output:
<b>Moe</b> <b>Larry</b> <b>Curly</b>
_.templateSettings = {
evaluate: /\{\{(.+?)\}\}/g,
interpolate: /\{\{=(.+?)\}\}/g,
escape: /\{\{-(.+?)\}\}/g
};
View:
artistArray = ["biggie", "mike", "taylor"];
var listTemplate = _.template($("#listTemplate").html());
listTemplate(listTemplate);
Template:
<script id="listTemplate" type="text/template">
<ul class="artists">
<%% _.each(artistArray, function(title, index){ %>
<li data-index="<%%= index %>">
<%%= title %>
</li>
<%% }); %>
</ul>
</script>
Output:
<ul class="artists">
<li data-index="0"> biggie </li>
<li data-index="1"> mike </li>
<li data-index="2"> taylor </li>
</ul>