Vincec's Dimension

Some examples of using Mustache templates.

Word count: 392 / Reading time: 2 min
2018/07/03 Share

Just found Mustache is an elegent but powerful minimal templating tool. It supports many languages. Here is some notes of example for using Mustache in JavaScript.

Add mustache.js file

mustache.min.js

1
<script src="../js/mustache.min.js"></script>

The example from official tutorial

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//A typical Mustache template:
Hello {{name}}
You have just won {{value}} dollars!
{{#in_ca}}
Well, {{taxed_value}} dollars, after taxes.
{{/in_ca}}
Given the following hash:

{
"name": "Chris",
"value": 10000,
"taxed_value": 10000 - (10000 * 0.4),
"in_ca": true
}

//Will produce the following:

Hello Chris
You have just won 10000 dollars!
Well, 6000.0 dollars, after taxes.

Single html file using Mustache.js

Mustache.js example

index.html
1
2
3
4
5
<div id="target"></div>

<script id="template" type="x-tmpl-mustache">
<p>Use the <strong></strong>, !</p>
</script>
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
window.onload = function() {
//Grab the inline template
var template = document.getElementById('template').innerHTML;

//Parse it (optional, only necessary if template is to be used again)
Mustache.parse(template);

//Render the data into the template
var rendered = Mustache.render(template, {name: "Luke", power: "force"});

//Overwrite the contents of #target with the rendered HTML
document.getElementById('target').innerHTML = rendered;
}

Mustache JS - Template Sample

index.html
1
2
3
4
5
6
7
8
9
<div id="output"></div>

<script type="text/html" id="test">
<h1></h1>
<span>Auhtor </span>
<span> </span>
<span>Category </span>
<span> </span>
</script>
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function(){ 

var template = $('#test').html();
var output = $('#output');

var data = {
"Book": "Rich Dad Poor Dad",
"Author": "Robert Kiyosaki",
"Category" : "Finance"
}

var result = Mustache.render(template, data);
output.append(result);

});

For Loop Sample

Mustache JS - For Loop Sample

index.html
1
2
3
4
5
6
7
8
9
<div id="output"></div>
<script type="text/template" id="test">
<h1>{{Subject}}</h1>
<ul>
{{#names}}
<li>{{name}}</li>
{{/names}}
</ul>
</script>
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(document).ready(function(){ 
var template = $('#test').html();
var output = $('#output');

var data = {
"Subject": "Template Engines",
"names": [
{"name": "Mustache"},
{"name": "HandleBar"}
]
};

var result = Mustache.render(template, data);

output.append(result);

});
CATALOG
  1. 1. Add mustache.js file
  2. 2. The example from official tutorial
  3. 3. Single html file using Mustache.js
    1. 3.1. Mustache.js example
    2. 3.2. Mustache JS - Template Sample
  4. 4. For Loop Sample
    1. 4.1. Mustache JS - For Loop Sample