Home MustacheJS MustacheJS

MustacheJS

1819
0

What is Templating?

Setup & Test Mustache
The Template & How to use Templates
Mustache Sections (loop)
Mustache Conditions (if)
Mustache Functions

What is JavaScript Templating?

It’s a way of combining data and presentation
But keeping them separate
Used to display a data collection

clubsAjaxJSON.js

...
xmlhttp.onreadystatechange = showJSONData;
xmlhttp.open("GET", "clubs.json", true);
xmlhttp.send();
...

function showJSONData() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    var data = JSON.parse(xmlhttp.responseText);
    var output = '<ul>';                     
    for (var i = 0; i < data.clubs.length; i++) 
      output += '<li>' + data.clubs[i].name + '</li>';      
    output += '</ul>';
    document.getElementById("myDiv").innerHTML = output;          
  }
}

not optimal way of doing this…

JavaScript Templating Solution

MustacheJS
MustacheJS

Input #1 – Data (e.g. JSON)
Input #2 – JS Template
Template engine combines both
Output is HTML presentation of your data

JavaScript Templating

Templates used in lots of places. e.g.

tweets
facebook posts
etc.

They use a specific presentation template to display content

Templating Engines

There are lot of them:

  • jQuery Template
  • Mustache
  • Dust
  • Handlebars
  • EJS

We’ll use Mustache… Why?

  • available for JavaScript, Java, PHP, Python and Node
  • Simple syntax
  • Extendable

Setup Mustache

Visit mustache.github.io
Goto JavaScript version
Download .js file to a Mustache folder

Hello Mustache Example

HelloMustache.html

<!DOCTYPE html>
<html>
<head> 
    <script type="text/javascript" src="mustache.js"></script>
    <script type="text/javascript">

    window.onload=function() {
        var template = document.querySelector("#template").innerHTML;
        var result = Mustache.render(template, {name: "Tom"});
        document.querySelector("#container").innerHTML=result;
    };

    </script>
</head>
<body>
<script id="template" type="text/template">
Hello {{name}}
</script>
<div id="container"></div>
</body>
</html>

Let’s explain this works…

The Template

<script id="template" type="text/template">
Hello {{name}}
</script>

Added to HTML page where data is to appear
Describes how to display the data
Can be any HTML tag set

How to Use the Template

Get template content
Render template
Put result into a HTML container

(1) Get template content

var template = document.querySelector("#template").innerHTML;

(2) Render the template

var result = Mustache.render(template, {name: "Tom"});

Mustache.render() is passed reference to template and a JSON object

(3) Put result into a HTML container

document.querySelector("#container").innerHTML=result;

Another Example

Station.html

<!DOCTYPE html>
<html>
<head> 
    <script type="text/javascript" src="mustache.js"></script>
    <script type="text/javascript" src="Station.js"></script>
</head>

<body>
<script id="stationTemplate" type="text/template">
    <div class="stationTemplateWrapper">
        <div>Station No: {{stno}}</div>
        <div>Name: {{name}}</div>
        <div>County: {{county}}</div>
    </div>
</script>

<h1>Stations</h1>
<div id="container"></div>
</body>
</html>

Station.js

window.onload=function() {
    var template = document.querySelector("#stationTemplate").innerHTML;
    var result = Mustache.render(template, {
            "stno": "2075",
            "name": "Finner",
            "county": "Donegal",
            "lat": "54.49",
            "lng": "-8.239"
        });
    document.querySelector("#container").innerHTML=result;
};

Mustache Sections (loop)

Sections are used for repeating a template with a data collection

Example template:

<div class="stationTemplateWrapper">
    {{#sectionName}}
        <div>{{field1}}</div>
        <div>{{field2}}</div>
        <div>{{field3}}</div>
    {{/sectionName}}
</div>

Open and close template with section name
Notice # and / symbols

Mustache Section Example

We’ll use the stations.js collection of objects
It’s a list of weather stations Met Eireann use throughout Ireland
Let’s use Mustache sections to print each station…Mustache Section Example

List Stations Example

listStations.html

<!DOCTYPE html>
<html>
<head> 
    <script type="text/javascript" src="mustache.js"></script>
    <script type="text/javascript" src="stations.js"></script>
    <script type="text/javascript" src="listStations.js"></script>
</head>

<body>
<script id="stationTemplate" type="text/template">
    {{#stations}}
    <div class="stationTemplateWrapper">
        <div>Station No: {{stno}}</div>
        <div>Name: {{name}}</div>
        <div>County: {{county}}</div>        
    </div>
    {{/stations}}
</script>
<h1>Stations</h1>
<div id="container"></div>
</body>
</html>

listStations.js

window.onload=function() {
    var template = document.querySelector("#stationTemplate").innerHTML;
    var result = Mustache.render(template,{"stations": stations});
    document.querySelector("#container").innerHTML=result;
};

Notice the need to use the stations key for the stations array
It must match the template section name

Mustache Conditions (if)

Mustache can use basic logical conditions
For example, you can check if data exists or not in a section/field
This is useful for checking data fields with falsy values:

  • string = “”
  • int = 0
  • false boolean values

Use the ^ symbol for the false condition

An example…

stationConditional.html

<!DOCTYPE html>
<html>
<head> 
    <script type="text/javascript" src="mustache.js"></script>
    <script type="text/javascript" src="stations.js"></script>
    <script type="text/javascript" src="stationConditional.js"></script>
</head>
<body>
<script id="stationTemplate" type="text/template">    
    <div>Station No: {{stno}}</div>
    <div>Name: {{name}}</div>
    {{#county}}
    <div>County: {{county}}</div>
    {{/county}}
    {{^county}}
    <div>County Unknown!!</div>
    {{/county}} 
</script>

<div id="container"></div>
</body>
</html>

stationConditional.js

window.onload=function()
{
    var template = document.querySelector("#stationTemplate").innerHTML;
    var result = Mustache.render(template,{
        "stno": "1",
        "name": "Wonderland",
        "county": ""
    });
    document.querySelector("#container").innerHTML=result;
}

Mustache Functions

First let’s look at JavaScript object methods/functions

JavaScript Object Functions

JS functions are actions that can be performed on objects

Take the object employee:

var employee = {
    "name": "John",
    "hours": 40,
    "rate": 5
};

add a function…

var employee = {
    "name": "John",
    "hours": 40,
    "rate": 5,
    "wage": function(){ 
              return this.hours*this.rate;
            }
};
console.log(employee.wage());  // prints 200

More…

You can add a function to a collection of objects too

var employees = [
    {"name": "John","hours": 40,"rate": 5},
    {"name": "Paul","hours": 25,"rate": 7.50}
];

for(var i=0;i<employees.length;i++)
    employees[i].wage = function(){
        return this.hours * this.rate;
     };

for(var i=0;i<employees.length;i++)
    console.log(employees[i].wage());  // prints 200 and 187.5

Let’s use functions in Mustache templates

Take this dataset of employee data:

var data = {
    "employees": [
        {"name": "John", "hours": 40, "rate": 5.00},
        {"name": "Paul", "hours": 25, "rate": 7.50}  
    ]
};

Let’s write an object function to calculate the weekly wage…

var data = {
    "employees": [
        {"name": "John", "hours": 40, "rate": 5.00},
        {"name": "Paul", "hours": 25, "rate": 7.50}  
    ]
};

for(var i=0;i<data.employees.length;i++)
{
    data.employees[i].wage = function(){
        return this.hours * this.rate;
    };
}

objectFunction.html

<!DOCTYPE html>
<html>
<head> 
    <script type="text/javascript" src="mustache.js"></script>
    <script type="text/javascript" src="objectFunction.js"></script>
</head>

<body>
<script id="employeeTemplate" type="text/template">
    <div class="stationTemplateWrapper">
        <table border=1><tr><th>Name</th><th>Wage</th></tr>
            {{#employees}}
            <tr>
            <td>{{name}}</td>
            <td>{{wage}}</td> <!-- invoking wage() function -->
            </tr>
            {{/employees}}
        </table>
    </div>
</script>
<div id="container"></div>
</body>

objectFunction.js

window.onload=function(){

    var data = {
        "employees": [
            {"name": "John", "hours": 40, "rate": 5.00},
            {"name": "Paul", "hours": 25, "rate": 7.50}  
        ]
    };

    // add object function wage()
    for(var i=0;i<data.employees.length;i++)
        data.employees[i].wage = function(){
            return this.hours * this.rate;
        };

    // render template
    var template = document.querySelector("#employeeTemplate").innerHTML;
    var result = Mustache.render(template,data);
    document.querySelector("#container").innerHTML=result;      
}

Previous articleD3 – SVG
Next articleUnderscoreJS