Skip to content

Instantly share code, notes, and snippets.

@kreativan
Created January 27, 2018 14:20
Show Gist options
  • Save kreativan/4754d8b01ad38ddeab603be5b702083a to your computer and use it in GitHub Desktop.
Save kreativan/4754d8b01ad38ddeab603be5b702083a to your computer and use it in GitHub Desktop.
jQuery Mustache.js
/**
* Basic Template
*/
var person = {
firstName: "Ivan",
lastName: "Milincic",
blogURL: "http://kreativan.net"
};
var template = "<h1>{{firstName}} {{lastName}}</h1>Website: {{blogURL}}";
var html = Mustache.to_html(template, person);
$('#SOME_ID').html(html);
/**
* Basic Template using Ajax data
*/
$.getJSON('json/data.json', function(data) {
var template = "<h1>{{firstName}} {{lastName}}</h1>Blog: {{blogURL}}";
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
});
/**
* Externalized Template
*/
$.getJSON('json/data2.json', function(data) {
var template = $('#personTpl').html();
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
});
<script id="personTpl" type="text/template">
<h1>{{firstName}} {{lastName}}</h1>
<p>Blog URL: <a href="{{blogURL}}">{{blogURL}}</a></p>
</script>
/**
* Enumerable Section
*/
var data = {name: "John Smith", skills: ['JavaScript', 'PHP', 'Java']};
var tpl = "{{name}} skills:<ul>{{#skills}}<li>{{.}}</li>{{/skills}}</ul>";
var html = Mustache.to_html(tpl, data);
$('#sampleArea').html(html);
/**
* Enumerable Section with Objects
*/
var data = {
employees: [
{ firstName: "Christophe",
lastName: "Coenraets"},
{ firstName: "John",
lastName: "Smith"}
]};
var template = "Employees:<ul>{{#employees}}" +
"<li>{{firstName}} {{lastName}}</li>" +
"{{/employees}}</ul>";
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
/**
* Nested Objects
*/
var person = {
firstName: "Christophe",
lastName: "Coenraets",
blogURL: "http://coenraets.org",
manager : {
firstName: "John",
lastName: "Smith"
}
};
var template = "<h1>{{firstName}} {{lastName}}</h1><p>{{blogURL}}</p>" +
"Manager: {{manager.firstName}} {{manager.lastName}}";
var html = Mustache.to_html(template, person);
$('#sampleArea').html(html);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment