TUTORIAL - Working with HTML Template Engines - Mustache.js
What Will I Learn?
We will focus in todays part how to work with mustache.js in an easy and basic way. This tutorial is part of a mini series where we will discuss the main HTML Template Engines and how to use them.
Requirements
- A TextEditior (e.g Atom.io)
- A Browser (e.g Chrome)
Difficulty
- Basic
Tutorial Contents
What is mustache.js ?
mustache.js is an implementation of the mustache template system in JavaScript.
Mustache is a logic-less template syntax. It can be used for HTML, config files, source code - anything.
It works by expanding tags in a template using values provided in a hash or object.
We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are
only tags. Some tags are replaced with a value, some nothing, and others a series of values.
Why should I use mustache.js ?
In many projects developer want to generate HTML files based on their variables / objects of their code. Also they do not want to change the complete DOM after it rendered. HTML Template Engines are a great alternative for this. They handle the template rendering according to your set variables, which is quite cool.
Mustache.js is pretty basic and really easy to use. - also it is logic-less.
Short project setup
Create a Project, with two files: index.html
and index.js
.
index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
<script src="index.js"></script>
</head>
<body>
</body>
</html>
index.js
console.log('Hello World');
Then open the index.html file inside your browser -> right-click -> inspect to check if you see an output with Hello World Text in it.
As you can see, we are using online services to get the scripts from. Which is okay for testing purposes since we know we have a valid internet connection.
Using examples
Let's begin easy: To call and use mustache.js we use the function named Mustache.render(template, data);
. The template parameter should be a valid string, data should be a valid object containing all the data you want to set in your template. Inside the template all variables we want to replace must be in double 'mustaches' -> {{...}} (yeah that's the reason for their name...).
A template can contain everything which is valid HTML, including mustaches !
A quick example
Edit your index.js as follows:
var data = {
name: "Moonrise",
sayHello: function () {
return 'Hello World';
}
};
var output = Mustache.render("{{name}} says: {{sayHello}}", data);
console.log(output);
Now reload your webpage and watch the output
- {{name}} got replaced for the value name in our data object
- {{sayHello}} got replaced for the returned value of the function sayHello in our data object
- This means, with mustache.js we are able to use functions and values!
Using templates
Using strings and replace their content ain't really special, because JavaScripts .replace
function is able to do this too. But mustache.js can do more ! In HTML we can declare template scripts
<script id="template" type="x-tmpl-mustache">
Hello {{ name }}!
</script>
We now got a template with the ID template and TYPE x-tmpl-mustache!
With this information it is easy for us to create a simple loading page, which renders a template as soon as mustache.js finished:
index.html
<body onload="onLoad()">
<div id="output">Loading...</div>
<script id="template" type="x-tmpl-mustache">
{{name}} says: {{sayHello}} !
</script>
</body>
When our body fully rendered onLoad
is called, it could before onLoad is called that some templates or divs aren't loaded yet. Which means that we can not access them in JavaScript.
Then we have our output div, where the content gets replaced with the rendered version of our template!
index.js
function onLoad() {
var data = {
name: "Moonrise",
sayHello: function() {
return 'Hello World';
}
}
var template = $('#template').html();
var output = Mustache.render(template, data);
$('#output').html(output);
}
We are using here the feature of jQuery $('#TAG-ID')
which gets us all elements inside our HTML with the same ID. (# is used for id-names, . are used for class-names). Also we used $('#template').html();
which basically returns the whole HTML text (inside the template script we wrote in our index.html
) as a String .
Reload your webpage and you will see the same output we had before, but now inside the webpage itself!
Using sub-variables
With mustache.js it is also possible to use sub-variables, meaning we could also write this inside our data object:
var data = {
name: {
first: 'Moon',
last: 'rise'
},
sayHello: function() {
return 'Hello World';
}
}
first and last are sub-variables/properties of the property name
!
To use it in a template simply write it in dot-notation {{name.first}} says: {{sayHello}} !
Using booleans
We can also use boolean values inside our mustache.js template to show or hide certain types!
index.html
<script id="template" type="x-tmpl-mustache">
{{name.first}} says: {{sayHello}} !
{{#isOver18}}
We got cookies here! Only over 18 allowed !
{{/isOver18}}
</script>
Add a new property to your data object named isOver18
and try around setting it to true of false, if true you will see the text and if false not.
Rerendering Templates
It is of course possible to rerender your templates. For example could we create a button which toggle our isOver18 text when clicked.
index.html
<body onload="onLoad()">
<button id="toggle-age">Switch Age</button>
<div id="output">Loading...</div>
<script id="template" type="x-tmpl-mustache">
{{name.first}} says: {{sayHello}} !
{{#isOver18}}
We got cookies here! Only over 18 allowed !
{{/isOver18}}
</script>
</body>
index.js
var data = {
name: {
first: 'Moon',
last: 'rise'
},
isOver18: false,
sayHello: function() {
return 'Hello World';
}
}
function onLoad() {
$('#toggle-age').click(function() {
data.isOver18 = !data.isOver18;
render(data);
});
render(data);
}
function render(data) {
var template = $('#template').html();
var output = Mustache.render(template, data);
$('#output').html(output);
}
$('#toggle-age').click(function() {..}
uses jQuery click function to react when the id toggle-age is clicked. We put the data object outside our onLoad function to maintain it's state better and edit it isOver18
state when the button is clicked. Then we rerender our template!
Thats basically it for this part. Mustache.js is able to do a lot more things, like Lists / advanced function use / etc... but we will talk about the advanced stuff in a future tutorial :)
I hope you guys enjoyed it !
What's next ?
Handlebars & doT
Curriculum
Not available since first part...
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been approved.
It is good that you have also marked the cited passage as a quote, but please always include the source of the quote.
You can contact us on Discord.
[utopian-moderator]
You've got upvoted by
Utopian-1UP
!You can give up to ten 1UP's to Utopian posts every day after they are accepted by a Utopian moderator and before they are upvoted by the official @utopian-io account. Install the @steem-plus browser extension to use 1UP. By following the 1UP-trail using SteemAuto you support great Utopian authors and earn high curation rewards at the same time.
1UP is neither organized nor endorsed by Utopian.io!
Hey @moonrise I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x
It's amazing tutorial Could you continue with another practical example with ajax technology ?