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

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix