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
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
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
| 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 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- New Products
- RSS Feeds
- Trying to Tame the Tablet
- What's the tweeting protocol?
- Dart: a New Web Programming Experience
- Drupal is an Awesome CMS and a Crappy development framework
4 hours 11 min ago - IT industry leaders
6 hours 34 min ago - Reply to comment | Linux Journal
23 hours 22 min ago - Reply to comment | Linux Journal
1 day 1 hour ago - Reply to comment | Linux Journal
1 day 3 hours ago - great post
1 day 3 hours ago - Google Docs
1 day 4 hours ago - Reply to comment | Linux Journal
1 day 8 hours ago - Reply to comment | Linux Journal
1 day 9 hours ago - Web Hosting IQ
1 day 11 hours ago







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