Introduction to JavaScript Templating [video tutorial] with Mustache.js

Recently, I did a small website for an event in my area. This type of project required me to manage small amounts of data. Information about speakers, bios, titles and a description of the talks. I wanted to have a Speaker’s page, but I also wanted a rotating promo as a component that I could use on the homepage and on other pages to promote the speakers. That means two different views for the same data.

This is the kind of problem I used to throw a quick SQL database at, but It really wasn’t worth the pain because the amount of data was so minimal. However I didn’t want to have to use HTML because I knew the information would change often enough to be a pain to update. To solve it, I used a library called mustache.js. It’s pretty easy to use and solves the problem with just a few lines of code.

Why Mustache.js?

Mustache is a library that allows you to read in JSON formatted data and display it using templates you design with JavaScript. There are lots of similar libraries like underscore.js, handlebars.js and dust.js. So why did I choose mustache?

I picked mustache because I wanted something simple. Some of the other libraries provide more functionality, but I didn’t need complexity. I needed to spend time building the site, not learning something new. And that’s the great thing about mustache.js. If you know JSON and a bit of JavaScript, it’s a cinch to implement. You do need to know how to use the JSON format, so If you’re not familiar with JSON, make sure you take a look at this article on Getting Started with JSON for beginners.

Installing or Using CDNs

As usual, you have two options for working with libraries. You can install them manually or use CDNs (Content Delivery Networks). Mustache is actually a format that has implementations available for different languages. If you want to download a copy, go to this Github page to download mustache.js. Because we’re going to be loading JSON files from an external source, you’ll also need to install jQuery, to download a copy of jQuery you can go to their website.

If you’re just experimenting with the libraries, another option is to load the files from a Content Delivery Network. A site that specializes in hosting popular libraries like cdnjs.com. In order to keep things simple for this article, I’m going to load things from that CDN.

Our data

Here’s what the structure of my data looked like (abbreviated). Just a simple object with an array with the usual information people would need to find out about the speakers.

Our course, my JSON file has a lot more information. Here’s the original JSON document with all of the information for this project.

Creating a page

Our page is going to be super simple. I’ll create a basic HTML document, and then create a <ul> tag with an id of talktitles. The list will be empty and will get filled up with data from our JSON file. I’ll also link in order to the jQuery and mustache.js libraries from the CDN.

Here’s what that code looks like.

Next, we’ll need to create the template. That’s pretty easy. You create a mustache.js template inside <script> tags. Normally, your page would interpret this as JavaScript and throw an error, but if we give the script the a type of text/template, the browser’s JavaScript parser will ignore it. Our template will also need an ID because it’s how we’ll refer to it when we use JavaScript to target it.

Crafting our template

Here’s the code for our template. It should go after our call to the jQuery library.

This should be pretty easy to read. We want to print the titles for each of our speakers. Our template is simply HTML with double curly braces where we want the library to generate code for us. So, to output the title, we simply use {{title}} to output that field from our JSON file. In order to loop through each of the speakers, we use the {{#speakers}} because it’s the name of the array containing all of the speakers.

The reason a lot of these libraries have names related to facial hair is because of the all of the curly braces they use. This technique of putting data from a data file into a template is known as data binding.

Calling the data

To have our data load from the template, we use jQuery’s getJSON method. I can read any JSON file. We can pass the data into a function. We’re using an anonymous function here (a function with no name).

Inside this we can then create a variable called template and then use the jQuery html() method to read the contents of our template into a variable. Then, we use that template and the data with a call to the Mustache.to_html method from mustache.js that will return the HTML with the JSON data merged with our template.

Finally, we use jQuery’s to place that HTML inside our unordered list with the id of talktitles. Here’s that code.

Putting it all together

Here’s a full listing of the code.

You might have a problem when trying to read the JSON document if you don’t put this code on a server. For security reasons certain browsers (Google Chrome) don’t allow you to load external files on local folders. You can try using Safari, or just load the file on a live server.

My Barcamp Deland project

For the final project, I used a more complicated template to drive the display of different elements on my page. The featured speakers rotating promo on the homepage as well as the data in the Speakers page. I also used this on a mobile app for the event, so changing a single text file updated the information in two or three places. You can see an example of the finished Barcamp Deland website to see a more complex example of the code.

8 thoughts on “Introduction to JavaScript Templating [video tutorial] with Mustache.js

  1. Tom B

    Ray, great tutorial, I am a newbie to java and jquery, and I successfully generated a carousel using json and mustache. However, I want to add more interactivity with some additional jquery and I can’t seem to select any of the mustache generated selectors (ex: {{title}}) renders well, but when I want modify it with jquery ( $(“h4.listing”)) I can’t select it or any other item in the mustache template. Can tell me if it is possible to modify the mustache HTML?

    Reply
    1. Ray Villalobos

      That’s really odd. I would make sure that I use the Developer tools in Google to detect what the rendered output looks like. There’s no reason why you shouldn’t be able to modify the created dom after the fact. Try using pure javascript’s querySelector instead.

      Reply
  2. Alejandro

    Hi, very nice tutorial, im quite new in this,

    If i have a big template, or many templates, and dont want to add them inside the

    can i write and then call them as external templates files?

    How can i do this?

    thanks

    Alejandro

    Reply

Leave a Reply