Mustache.js

In previous articles, I've looked at a number of uses for JavaScript, on both the server and the client. I hope to continue my exploration of such systems, particularly on the client side, in the coming months.

But for now, I want to tackle a more mundane problem that JavaScript programmers encounter all the time: the fact that JavaScript doesn't have any native string-interpolation mechanism. Sure, you always can use the + operator to concatenate strings:


"hello, " + "world"

which gives you the string:


"hello, world"

which is what you might expect. But, what if you have a variable "username", and you want to say "hello" to the user in a friendly way? In Ruby, you would use:


"hello, #{username}"

And in Python, you would write:


"hello, %s" % username

But in JavaScript, you're basically stuck typing:


"hello, " + username

which isn't so terrible if you have one variable at the end of the string. But the more I'm working with JavaScript, the more I'd like to have more sophisticated string interpolation.

While I'm wishing, I'd like to have all sorts of text-formatting and templating capabilities that I'm used to from other languages or from various Web frameworks.

Now, this doesn't sound like a tall order. And heaven knows, I've used a lot of templating systems during the years, so I know that it's not very hard to create one—especially if the standards aren't very high. But as Web applications become more heavily focused on the browser, and on JavaScript, you'll need a templating solution that allows you to work easily in that environment.

Fortunately, several templating systems exist. One of the most prominent and interesting is Mustache.js, a JavaScript implementation of the Mustache templating system that is available for many different languages. In contrast with most other templates I've used, Mustache.js is not a fully fledged programming language, as you might expect. Rather, it's a tightly defined domain-specific language that describes the page, but that doesn't have the potential to make templates into another code repository.

So, this article explores Mustache.js—how to install and use it, as well as when it's appropriate and how to use a few of the more-advanced features that come with it.

Templates

Many readers probably are familiar with a typical sort of template, with a style used by PHP, ASP, JSP and Ruby's ERb. Anything that should be executed goes in braces that look like this:


<% varname = 5 %>

And, anything you want to display on the screen gets nearly the same sort of tag, but with an = sign on the left:


<%= varname %>

The good news with such templates is that they're rather easy to use. You don't have to worry about which symbols mean what, or set up a file just to see some interpolated variables. But on the other hand, they're too simple for producing large-scale reports and certainly for doing serious text manipulation.

The other problem is that as soon as you put code into your template, you're violating the rule of MVC, which is that you don't want to put very much executable code in your template. Assigning variables isn't a good idea, but calling methods, not to mention retrieving rows from the database, is something you normally don't want to be doing within your views. But, you can be even stricter in how you interpret this no-execution policy. What if you could avoid all executable code, including if/then statements, loops and other things to which you're accustomed?

Mustache adopts this philosophy in that it allows for a limited set of things to take place within the template. You could argue (and I'd probably believe you) that it's going too far to say, as the Mustache slogan says, that they're "logic-less templates". Indeed, Mustache templates do have a fair amount of logic in them. But the nature of the templating language ensures that the special functions cannot be abused too terribly. If you want to execute code, you'll have to do it outside the realm of Mustache.

(If you're wondering, it's called Mustache because it uses double-curly braces, {{ and }}, as delimiters. Double-curly braces indicate where you want interpolation to take place, and they also delimit various control structures.)

Installing Mustache.js couldn't be easier. Download the single mustache.js file from GitHub, put it in an appropriate directory inside the JavaScript directory for your Web application—or alongside your HTML file, if you're just experimenting with it outside a framework—and you're ready to go.

Note that the inclusion of Mustache.js doesn't turn your HTML file (or your JavaScript file, for that matter) into a Mustache template. Rather, it provides you with a number of functions that can be applied to text strings. You then can do whatever you want with those text strings, from inserting them into a file to using them for further processing.

Listing 1 contains a simple example of using Mustache.js. At the top of the <head> section, I include both the jQuery library and Mustache.js, as I often would in an HTML file. I then have a bit of JavaScript code executing in the standard $(document).ready function call, ensuring that it will be executed only after jQuery has detected that the entire HTML document has loaded. This avoids a race condition, in which the JavaScript might or might not run before the HTML has been rendered.

Listing 1. Simple Use of Mustache


<!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',
     number_of_children: 3
     }

     var template = "<b>{{name}}</b> has 
     ↪{{number_of_children}} children.";
     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>
______________________

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