An Overview of JavaScript Templating Engines

Jamie Shields
Share

This article was peer reviewed by Chris Perry and Ritesh Kumar. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

In this article we’re going to give an overview of templating in JavaScript. We’ll first discuss what JavaScript templates are, when we should use them and how we implement them, before going into a bit more detail regarding some of the popular templating engines out there. We’re going to focus on Mustache, Handlebars and jQuery Template.

What Are JavaScript Templates?

JavaScript templates are a method of separating HTML structure from the content contained within. Templating systems generally introduce some new syntax but are usually very simple to work with, especially if we’ve used templating systems elsewhere previously (eg. Twig in PHP). A fun point to note is that token replacement is usually symbolized by double curly brackets ({{ ... }}), which Mustache and Handlebars derive their names from (hint: turn them sideways to see the similarity).

When Should We Use JavaScript Templates?

As soon as we find ourselves including HTML inside JavaScript strings we should be starting to think about what benefits JavaScript templates could give us. Separation of concerns is of utmost importance when building a maintainable codebase, so anything which can help us achieve this should be explored. In front-end web development this is epitomized when separating HTML from JavaScript (this works both ways in that we shouldn’t include JavaScript inline in HTML).

Some common scenarios which could benefit from JavaScript templates are real-time web apps (for example a live streaming app for event commentary), or internationalization (i18n), which will quite often require that different content is displayed using the same formatting.

How Do We Implement JavaScript Templates?

We’ll go into more detail on this with specific library examples, but essentially it’s as simple as including our chosen library, fetching our template and rendering it alongside some data.

Most libraries support both inline and external templates. Inline templates are great for when we’ve got very few templates or we know that we’ll be using the included templates on each page load, but generally our templates should be external. External templates bring many benefits, chiefly that templates will never be downloaded to the client unless they are needed by the page.

mustache.js

Mustache is a multi-language, logic-less templating system. The mustache.js implementation is just one of many. So once we’re used to the (very simple) syntax, we can use it in a variety of programming languages.

Key Points

  • 9kb file size (small)
  • Simple
  • No dependencies
  • No logic
  • No precompiled templates
  • Programming language agnostic

Example

<script id="template" type="x-tmpl-mustache">
  <p>Use the <strong>{{power}}</strong>, {{name}}!</p>
</script>

//Grab the inline template
var template = document.getElementById('template').innerHTML;

//Parse it (optional, only necessary if template is to be used again)
Mustache.parse(template);

//Render the data into the template
var rendered = Mustache.render(template, {name: "Luke", power: "force"});

//Overwrite the contents of #target with the rendered HTML
document.getElementById('target').innerHTML = rendered;

See the Pen Mustache.js example by SitePoint (@SitePoint) on CodePen.

As you can see in this example, the Mustache.render function takes two parameters: the Mustache template, as well as a view object that contains the data and code needed to render the template. In this case we are replacing name and a power variables with simple strings, but it’s possible to do much more. For example loop over an array, or make use of a special rendering function that uses the current view as its view argument.

mustache.js is perfect for small projects and quick prototypes where templating complexity is at a minimum. A key thing to note is that we can start off a project with mustache.js and then easily upgrade to Handlebars.js later as the templates are (mostly) the same.

If you would like to read more about Mustache, check out: Creating HTML Templates with Mustache.js.

Handlebars.js

Handlebars.js is built on top of Mustache and is mostly compatible with Mustache templates. In a nutshell, it provides everything mustache.js provides, plus it supports block expressions and precompiled templates. Precompiled templates are a big deal as they increase performance by a large margin (in a rough performance test, precompiled Handlebars.js templates rendered in about half the time of Mustache templates). Block expressions allow you to include more logic in your templates; one of the more common examples of these are advanced iterators — eg. create a <ul> list iterator which wraps each item in <li>. You can read more about block expressions here.

Key Points

  • 86kb file size (large), or 18kb if using precompiled templates
  • Block expressions (helpers)
  • Precompiled templates
  • No dependencies

Example

<script id="template" type="text/x-handlebars-template">
  <p>Use the <strong>{{power}}</strong>, {{name}}!</p>
</script>

//Grab the inline template
var template = document.getElementById('template').innerHTML;

//Compile the template
var compiled_template = Handlebars.compile(template);

//Render the data into the template
var rendered = compiled_template({name: "Luke", power: "force"});

//Overwrite the contents of #target with the renderer HTML
document.getElementById('target').innerHTML = rendered;

See the Pen Handlebars.js Example by SitePoint (@SitePoint) on CodePen

Handlebars.js is perfect for projects where performance is important and we are not hugely worried about adding 18kb to the weight of the page. It’s also the way to go if we want to make use of block expressions.

Note that to see the performance benefits of Handlebars.js (and the greatly reduced file size) we must use precompiled templates. In order to do so efficiently we should add Handlebars.js template compilation into our build process (Grunt has a great plug-in for this).

If you would like to find out more about Handlebars, check out: A Beginner’s Guide to Handlebars.

jQuery Template

jQuery Template is not as popular as mustache.js or Handlebars.js but we should not overlook it. The templates are different to Mustache templates as they are just plain HTML with no new syntax. Instead of token replacement techniques it uses data attributes to indicate where data should be inserted in the HTML fragment.

Key Points

  • 7kb file size (small)
  • Requires jQuery (+82kb)
  • Simple, but different to how Mustache and Handlebars.js work
  • No precompiled templates

Example

<script id="template" type="text/html">
  <p>
    Use the <strong data-content="power"></strong>, 
    <span data-content="name"></span>!
  </p>
</script>

//Call .loadTemplate() on the target container
$('#target').loadTemplate(
  //Specify the template container (or file name of external template)
  $('#template'),

  //Specify the data to render
  {
    name: "Luke",
    power: "force"
  }
);

See the Pen jQuery Template example by SitePoint (@SitePoint) on CodePen.

jQuery Template is ideal for projects which are already including jQuery as the file size is very small. However if your project is not going to utilise jQuery then it’s hard to recommend considering the total file size.

Other Options

There are of course many other solutions to this problem which we won’t cover in detail in this article. Here’s a very quick overview of some other popular choices;

Underscore.js

Underscore is a popular JavaScript library which provides templating functions amongst a myriad of other features. By default it does not use the double curly bracket syntax used by Mustache, instead opting for ERB-style delimiters (<% ... %>).

Embedded JS Templates (EJS)

Like Underscore.js, Embedded JS Templates uses ERB-style syntax for templates. One thing to note with EJS is that templates must be external files – they cannot be inline.

Closing Remarks

So which is the best? Like most development problems, there’s no silver bullet. It depends on many things;

  • Are you already using jQuery in your project?
  • Which templating systems do you have previous experience with?
  • Do you want to keep logic out of the templates?
  • How worried are you about total page file size?
  • How worried are you about performance/Does your website need to support low-power devices?

Once we’ve thought about those factors we can make an educated choice from the list above. However as briefly mentioned before, a good flexible strategy would be to implement mustache.js first and then swap to Handlebars.js later if the added functionality or performance benefits are needed.

Want to chime in? Please leave a comment below!