Mustache.js

I then define a variable (template_vars), a JavaScript object with two properties, "name" and "number_of_children". These properties can be of any data type, including a function. If a property is a function, it is evaluated when interpolated, and the result of the function's evaluation is inserted into the template.

I've then broken up the interpolation into three distinct parts. First, I define the text (the "template" variable) into which I want to interpolate variables. Notice how the string is a tiny template, and that anything within {{ }} (double-curly braces) is evaluated as a variable by Mustache.js.

Next, you apply your template_vars to the template, getting some HTML back. You then can do whatever you want with that HTML, including (most easily) replacing the text from an existing HTML tag. You also could have created a new node, replaced an existing one or modified the text even further.

In the end, I did something fairly simple, namely using jQuery's "html" function to replace the existing HTML with the improved version.

For something a bit more complex, which resembles traditional HTML templates a bit more, consider Listing 2. In this example, I decided to do a Mad Libs sort of replacement, but instead of changing text in a string, I changed it in the document itself. Using jQuery's selectors, I chose all elements with a "template" class. (This allows the author of the page to decide whether the {{ }} tags will be used on a particular tag.)

Listing 2. Replace Text in the Template


<!DOCTYPE html>
<html>
<head>
<h3>Testing</h3>

<script src="jquery.js"></script>
<script type="text/javascript" src="mustache.js"></script>

<script type="text/javascript">
     $(document).ready(
     function () {
     var template_vars = {
     proper_noun: 'Reuven',
     color: 'green',
     food: 'ice cream'
     }

     $(".template").each(function(index, value) {
     var current_html = $(this).html();
     var translated = Mustache.to_html(current_html, template_vars);
     $(this).html(translated);
     });

     });
</script>

</head>
<body>
<h1>Testing testing</h1>
<p>This is a paragraph</p>
<p class="template">My name is {{proper_noun}}.</p>
<p class="template">I like to wear {{color}} shirts, 
and eat {{food}} for breakfast.</p>
</body>
</html>

Perhaps the most interesting and important part of this code is the callback function I used to do the translation. Rather than using a typical jQuery loop, which would have turned into a rat's nest of code, I decided to use the "each" function, which iterates over a collection. In each iteration, $(this) refers to the item, and you next use the Mustache.to_html function to translate it, and then replace the text with its transformed self. In this way, your JavaScript easily can affect the text on the page.

What happens if you ask Mustache to use a variable value that you have not defined? It continues silently, using an empty string. This means that if your template_vars variable contains one or more keys with misspelled names, you won't get any warnings.

Loops and Conditionals

Remember when I wrote that I wouldn't call Mustache.js "logic-less templates", because the templating language still includes conditionals? Well, now you can see what I meant. (I should add that I'm fairly convinced I normally don't want code to be evaluated/executed in the template. But, conditionals and loops are two things that every useful templating system I've had has incorporated, and they are a necessary piece of logic for templates to be useful.)

If you look at Listing 3, you'll see how to create loops. I have added an array ("children") inside my template_vars variable. But instead of saying {{children}} to retrieve the contents of the array, you instead say {{#children} at the beginning of the loop and {{/children} at its end. Mustache.js is smart enough to know what to do, and it repeats the block within these delimiters, once for each element of the array. To get the current array element itself, you use the special syntax {{.}}.

Listing 3. Loops


<!DOCTYPE html>
<html>
<head>
<h3>Testing</h3>

<script src="jquery.js"></script>
<script type="text/javascript" src="mustache.js"></script>

<script type="text/javascript">
     $(document).ready(
     function () {
     var template_vars = {
     name: 'Reuven',
     children: ['Atara', 'Shikma', 'Amotz']
     }

     var template = "<b>{{name}}</b> has children
     ↪named:<ul>{{#children}}<li>{{.}}</li>{{/children}}.</ul>";
     var html = Mustache.to_html(template, template_vars);
     $('#target').html(html);
     });
</script>


</head>
<body>
<h1>Testing testing</h1>
<p>This is a paragraph</p>
<p id="target">This space for rent</p>
</body>
</html>

That's certainly some degree of logic, but it's nothing compared with the {{#mycondition}} tag, which begins the equivalent of an if-then statement. But wait, what are you checking? Well, if you're starting your condition with {{#mycondition}}, that means you're going to treat "mycondition" as a function, evaluating it at runtime and then displaying only the contents of the block (that is, the stuff between {{#mycondition}} and {{/#mycondition}} if the function returns "true").

Mustache has a bunch of other features too. It automatically escapes HTML by default, but it has a mechanism, {{{ }}}, that uses raw HTML, without cleaning up the < and > symbols that can be both annoying and potentially dangerous. So, you have the flexibility to replace text as appropriate in your application.

The examples I have provided obviously are somewhat contrived and simple. Fortunately, the syntax of Mustache.js is simple enough that it shouldn't take very long at all to incorporate it into your work.

Conclusion

Mustache is a straightforward, but powerful, templating system for JavaScript. If you're starting to put together a Web application that needs to rewrite parts of the text based on AJAX calls or JavaScript output, or if you're writing a one-page JavaScript-based application, you certainly should look into Mustache.js. The home page on GitHub has good documentation, and other tutorials and documents are linked from there as well.

Resources

The home page for Mustache is http://mustache.github.com.

For an interesting analysis of Mustache.js, as well as where it could be improved (and a description of a fork), read Yehuda Katz's blog entry at http://yehudakatz.com/2010/09/09/announcing-handlebars-js.

Mustache photo via Shutterstock.com

______________________

Reuven M. Lerner, Linux Journal Senior Columnist, a longtime Web developer, consultant and trainer, is completing his PhD in learning sciences at Northwestern University.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Thank you for that.

deeprock2's picture

Thank you for it. interesting, for me :)

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState