Quick Tip: Using the Mustache Template Library


Not long ago, I demonstrated how to use the Microsoft’s jQuery template plugin; in this quick tip, I’ll show you how to use a different template library, Mustache, which is just as easy to use.


View 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:

 <script src="http://github.com/janl/mustache.js/raw/master/mustache.js"></script>

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.

var data = {
    name : "Some Tuts+ Sites",
    sites: ["Nettuts+", "Psdtuts+", "Mobiletuts+"],
    url : function () {
        return function (text, render) {
            text = render(text);
            var url = text.trim().toLowerCase().split('tuts+')[0] + '.tutsplus.com';
            return '<a href="' + url + '">' + text + '</a>';
        }
    }
};

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:

<h1> {{name}} </h1>

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(/).

<ul>
    {{#sites}}

        <li> {{.}} </li>

    {{/sites}}
</ul>

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:

html = Mustache.to_html(template, data);

Then, you can stick that HTML wherever you want.


The Complete Source

var data, template, html;

data = {
    name : "Some Tuts+ Sites",
    sites: ["Nettuts+", "Psdtuts+", "Mobiletuts+"],
    url : function () {
        return function (text, render) {
            text = render(text);
            var url = text.trim().toLowerCase().split('tuts+')[0] + '.tutsplus.com';
            return '' + text + '';
        }
    }
};

template = "

{{name}}

    {{#sites}}
  • {{#url}} {{.}} {{/url}}
  • {{/sites}}
"; html = Mustache.to_html(template, data); document.write(html)

Conclusion

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

Leave a Reply

Your email address will not be published. Required fields are marked *