Advertisement
JavaScript & AJAX

Using the Mustache Template Library

by

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:

 <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(&#39;tuts+&#39;)[0] + &#39;.tutsplus.com&#39;; 
            return &#39;<a href="&#39; + url + &#39;">&#39; + text + &#39;</a>&#39;; 
        } 
    } 
};

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 '<a href="' + url + '">' + text + '</a>'; 
        } 
    } 
}; 
  
template = " 
<h1> {{name}} </h1>  
<ul> {{#sites}} 
<li> {{#url}} {{.}} {{/url}} </li>  
  
 {{/sites}}  </ul>  
  
"; 
  
html = Mustache.to_html(template, data); 
  
document.write(html)

Conclusion

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

Related Posts
  • Code
    HTML5
    HTML5: Battery Status APIPdl54 preview image@2x
    The number of people browsing the web using mobile devices grows every day. It's therefore important to optimize websites and web applications to accommodate mobile visitors. The W3C (World Wide Web Consortium) is well aware of this trend and has introduced a number of APIs that help with this challenge. In this article, I will introduce you to one of these APIs, the Battery Status API.Read More…
  • Web Design
    UX
    Walk Users Through Your Website With Bootstrap TourTour retina
    When you have a web application which requires some getting used to from your users, a walkthrough of the interface is in order. Creating a walkthrough directly on top of the interface makes things very clear, so that's what we're going to build, using Bootstrap Tour.Read More…
  • Code
    PHP
    Creating a Photo Tag Wall With Twilio Picture Messaging & PHPProcedural to oop php retina preview
    Twilio's recently announced Picture Messaging has vastly opened up what we can do with text messaging, now we can attach photos to our text messages and have them get used in different ways. In our case, we are going to build a Photo Tag Wall, which will contain photos linked to tags that will be displayed on a website.Read More…
  • Code
    JavaScript & AJAX
    Ember Components: A Deep DiveEmber components retina preview
    Ember.js is a JavaScript MVC framework that allows developers to create ambitious web applications. Although pure MVC allows a developer to separate concerns, it does not provide you with all the tools and your application will need other constructs. Today, I'm going to talk about one of those constructs. Ember components are essentially sandboxed re-usable chunks of UI. If you are not familiar with Ember, please check out Getting Started With Ember.js or the Let's Learn Ember Course. In this tutorial, we will cover the Web Components specification, learn how to write a component in Ember, talk about composition, explain the difference between an Ember view and an Ember component, and practice integrating plugins with Ember components.Read More…
  • Code
    JavaScript & AJAX
    Getting Into Ember.js: Part 5Getting into ember
    Editor's Note: The Ember.js team has shifted to an expedited release schedule and as of this publication date are on version 1.2.0. This tutorial was written pre-v1.0 but many of the concepts are still applicable. We do our best to commission timely content and these situations happen from time-to-time. We'll work to update this in the future. In part 3 of my Ember series, I showed you how you can interact with data using Ember's Ember.Object main base class to create objects that define the methods and properties that act as a wrapper for your data. Here's an example:Read More…
  • Code
    JavaScript & AJAX
    Handlebars.js - a Behind the Scenes LookHandlebars behind scenes retina preview
    Handlebars has been gaining popularity with its adoption in frameworks like Meteor and Ember.js, but what is really going on behind the scenes of this exciting templating engine? In this article we will take a deep look through the underlying process Handlebars goes through to compile your templates.Read More…