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>
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
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.
Sponsored by ActiveState
Web Development News
Developer Poll
| Non-Linux FOSS: libnotify, OS X Style | Jun 18, 2013 |
| Containers—Not Virtual Machines—Are the Future Cloud | Jun 17, 2013 |
| Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer | Jun 12, 2013 |
| Weechat, Irssi's Little Brother | Jun 11, 2013 |
| One Tail Just Isn't Enough | Jun 07, 2013 |
| Introduction to MapReduce with Hadoop on Linux | Jun 05, 2013 |
- Containers—Not Virtual Machines—Are the Future Cloud
- Non-Linux FOSS: libnotify, OS X Style
- Linux Systems Administrator
- Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer
- Validate an E-Mail Address with PHP, the Right Way
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- RSS Feeds
- Introduction to MapReduce with Hadoop on Linux
- user namespaces
17 min 55 sec ago - yea
43 min 44 sec ago - One advantage with VMs
3 hours 12 min ago - about info
3 hours 45 min ago - info
3 hours 46 min ago - info
3 hours 47 min ago - info
3 hours 49 min ago - info
3 hours 50 min ago - abut info
3 hours 52 min ago - info
3 hours 53 min ago







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