Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  1. Code
  2. JavaScript

Using the Mustache Template Library

Read Time:3 minsLanguages:

A while ago, I showed you how to use the jQuery template plugin in a quick tip; in this quick tip, I’ll show you how to use another template library, Mustache, which is just as easy to use.

Full Screencast

Step 1: Download Mustache

You can get Mustache.js from its GitHub project page; if you’re going to use it in a project, you can download it or git clone it; I’ve just referenced the raw file on GitHub for this quick tip:

Now you can use it to render data!

Step 2: Get Your Data

Most likely, you’ll be getting your data from the server in the form of JSON when you’re using Mustache in production. However, it’s just as easy to hard-code an object literal and use that, which is what we’ll do here.

Now we’re ready to define the template.

Step 3: Create your Template

Your template is simply string; you can either use a regular old JavaScript string, or you can put the template in a script tag and get it via something like jQuery’s html() method (or, of course, innerHTML). This is probably a better choice if you’re using a complicated template, because you can use line breaks. Just remember to give the script a type of something other than “text/javascript”; otherwise, browsers may try to interpret it, and that will cause errors.

Your template will be mainly HTML; when you want to use a value from your data, reference the key name of the value in the data. To use the name value in the data above, you’d reference it like this:

Blocks are an important piece of Mustache: you can use them to get inside arrays and objects, as well as for lambdas (functions). It’s pretty simple to do blocks: just use an opening and closing tag: the opening one starts with a pound (#) and the closing one with a slash(/).

When iterating over arrays, the implicit operator ”.” will get you the value. If sites was an object, you’d use it’s keys inside the block.

Using functions is a little more tricky. For the data part, Mustache.js requires a function that returns the function to be used. That function gets passed the text to be rendered (all the text within the mustache function tags) and a function that will render the template tags inside the text. Then, whatever that function returns will be put within the tags. You can see this at work in the urls function in the data above.

Step 4: Render the HTML

It’s really simple to render the HTML:

Then, you can stick that HTML wherever you want.

The Complete Source


To learn more about Mustache, check out the website. Have fun with it!

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.