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
Senior Columnist, Linux Journal
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
Web Development News
Developer Poll
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- Designing Electronics with Linux
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Dynamic DNS—an Object Lesson in Problem Solving
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Build a Skype Server for Your Home Phone System
- Why Python?
- A Topic for Discussion - Open Source Feature-Richness?
- Tech Tip: Really Simple HTTP Server with Python
- Great
3 hours 27 min ago - Reply to comment | Linux Journal
3 hours 35 min ago - Understanding the Linux Kernel
5 hours 49 min ago - General
8 hours 19 min ago - Kernel Problem
18 hours 22 min ago - BASH script to log IPs on public web server
22 hours 49 min ago - DynDNS
1 day 2 hours ago - Reply to comment | Linux Journal
1 day 2 hours ago - All the articles you talked
1 day 5 hours ago - All the articles you talked
1 day 5 hours ago







Comments
Thank you for that.
Thank you for it. interesting, for me :)