Mustache.js - Simple JS Templating Solution

What is Mustache?

Mustache is a templating framework for many languages that helps you to organize code by abstracting the HTML and visual portions of the code from the logic. This post is specifically for Mustache.JS and discusses getting started with the Javascript templating, but you can download code to use mustache with many different languages from the Mustache Github

Getting Started

Either Download Mustache.js from the Mustache Github or include Mustache.js & Jquery in your html file:

The HTML

In this example, we will create a list of links which can be used as navigation links. The links will be populated through Javascript and placed into the HTML by using a template.
In the body portion of your HTML, create an unordered list and give this list the Id of topnav.

The Template

In your html file, you will create a template, which will be a combination of HTML and placeholder variables. The placeholder variables will be populated with content through Javascript.
In this case, we will be looping through a list of link objects which have a url and title property. To specify a repetitive block of code in mustache, you will have a start and end tag with the name of the objects.
Note: It is important that the JSON object is formatted to match your template. So, in this case, our template will specify the block name as links and the attribute names as url and title.

The JavaScript

Write a JQuery script to populate the template. The template will be populated with a JSON object formatted to match the structure of your template. This can be pulled dynamically with AJAX from a service. In this example, I create the JSON string in a variable called data so you can see how the format matches.
In this example, the JavaScript is in an External File included AFTER mustache and Jquery are included. The file is called getLinks.js.

Full Code for this project

index.html
getLinks.js

Comments