How to fill a MustacheJS template at compile-time and inject it into a webpage
You've used MustacheJS templating to avoid code repetition and you're now dynamically filling in the template at run time.
This works great, however you know that the user wastes time while the library is downloaded and the template is filled, when this could very well be done before hand, at compile time.
You're very well aware of tools like Gulp for this kind of tasks, but how exactly would you set up MustacheJS compiling? And how to insert the compiled HTML in the page?
Let's walk through this step by step while bulding a page to display a list of coffees ☕☕☕.
1. Initial setup
We start off from a very simple setup, just an index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testing mustache</title>
<script src="bower_components/mustache.js/mustache.js"></script>
</head>
<body>
<h1>Coffees of the day</h1>
<div id="content"></div>
<script id="template" type="x-tmpl-mustache">
<ul>
{{#coffees}}
<li>{{name}}</li>
{{/coffees}}
</ul>
</script>
<script>
var data = {
"coffees": [
{ "name": "Espresso" },
{ "name": "Capucinno" },
{ "name": "Flat white" },
{ "name": "Ristretto" }
]
};
var template = document.getElementById('template').innerHTML;
var output = Mustache.render(template, data);
document.getElementById('content').innerHTML = output;
</script>
</body>
</html>
2. Convert the index.html into a template
The first thought you might have is to extract the template and the data, run mustache
on them and then inject the generated HTML into the main HTML file.
But this is just the kind of thing that Mustache knowns how to handle, so why not just make the index.html
also a template?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testing mustache</title>
</head>
<body>
<h1>Coffees of the day</h1>
<div id="content">
<ul>{% raw %}
{{#coffees}}
<li>{{name}}</li>
{{/coffees}}{% endraw %}
</ul>
</div>
</body>
</html>
Notice how all the code for rendering the template at runtime is gone and so is the <script>
tag to include mustache.js
.
Let's prepare the data for the template now, by extracting the coffeee list into a separate coffees.json
file:
{
"coffees": [
{ "name": "Espresso" },
{ "name": "Capucinno" },
{ "name": "Flat white" },
{ "name": "Ristretto" }
]
}
3. Pass through gulp
We will generate the final HTML files into a dist
folder. This is how the folder structure looks right now:
- dist
- index.html // compiled file
- templates
- index.html // source file
- coffees.json
- Gulpfile.js
To setup the Gulp task, we'll use gulp-mustache:
var gulp = require('gulp');
var mustache = require('gulp-mustache');
gulp.task('mustache', function() {
gulp.src('templates/*')
.pipe(mustache('coffees.json'))
.pipe(gulp.dest('./dist'));
});
To compile, just run gulp mustache
;
4. Done!
The built website is now under the dist
folder, which you can now copy to your live server.