Home > Web Front-end > JS Tutorial > An Overview of JavaScript Templating Engines

An Overview of JavaScript Templating Engines

Christopher Nolan
Release: 2025-02-18 09:18:11
Original
763 people have browsed it

An Overview of JavaScript Templating Engines

An Overview of JavaScript Templating Engines

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.

Key Takeaways

  • JavaScript templates offer a method of separating HTML structure from content, improving the maintainability of the codebase. They are particularly beneficial for real-time web apps and internationalization, which often require different content to be displayed using the same format.
  • Mustache.js is a multi-language, logic-less templating system ideal for small projects and quick prototypes. It’s simple, has no dependencies, and does not require precompiled templates. Furthermore, projects can easily upgrade to Handlebars.js later as the templates are mostly identical.
  • Handlebars.js, built on top of Mustache, supports block expressions and precompiled templates, improving performance significantly. It’s suitable for projects where performance is crucial and adding 18kb to the page weight is not a concern. To see the performance benefits and reduced file size, precompiled templates must be used.
  • jQuery Template, though not as popular as Mustache.js or Handlebars.js, should not be overlooked. It requires jQuery and uses data attributes to indicate where data should be inserted in the HTML fragment. It’s ideal for projects already including jQuery due to its small file size. However, it’s not recommended for projects not utilizing jQuery considering the total file size.

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

<span><span><span><script</span> id<span>="template"</span> type<span>="x-tmpl-mustache"</span>></span><span>
</span></span><span><span>  <span><p>Use the <strong>{{power}}</strong>, {{name}}!</p>
</span></span></span><span><span></span><span><span></script</span>></span>
</span>
Copy after login
Copy after login
//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;
Copy after login
Copy after login

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

    list iterator which wraps each item in
  • . 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

    <span><span><span><script</span> id<span>="template"</span> type<span>="x-tmpl-mustache"</span>></span><span>
    </span></span><span><span>  <span><p>Use the <strong>{{power}}</strong>, {{name}}!</p>
    </span></span></span><span><span></span><span><span></script</span>></span>
    </span>
    Copy after login
    Copy after login
    //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;
    
    Copy after login
    Copy after login

    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

    <span><span><span><script</span> id<span>="template"</span> type<span>="text/x-handlebars-template"</span>></span><span>
    </span></span><span><span>  <span><p>Use the <strong>{{power}}</strong>, {{name}}!</p>
    </span></span></span><span><span></span><span><span></script</span>></span></span>
    Copy after login
    //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;
    
    Copy after login

    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!

    Frequently Asked Questions about JavaScript Templating Engines

    What are the key differences between JavaScript templating engines?

    JavaScript templating engines vary in terms of syntax, performance, and features. For instance, EJS is known for its simplicity and ease of use, while Handlebars.js offers powerful logic-less templates. Mustache.js is another popular choice due to its cross-language compatibility. It’s important to choose a templating engine that suits your project requirements and coding style.

    How do JavaScript templating engines improve web development?

    JavaScript templating engines streamline the process of generating HTML, making it easier to create dynamic web pages. They allow developers to separate the HTML structure from the data, leading to cleaner and more maintainable code. Templating engines also support reusable components, which can significantly reduce development time.

    Can I use multiple JavaScript templating engines in a single project?

    While it’s technically possible to use multiple templating engines in a single project, it’s generally not recommended. Using multiple engines can lead to code inconsistency and increased complexity. It’s best to choose one templating engine that fits your needs and stick with it throughout the project.

    How does a JavaScript templating engine work with Express.js?

    Express.js, a popular web application framework for Node.js, supports a wide range of templating engines. Once you’ve chosen a templating engine, you can set it as the default engine in Express.js. This allows you to render views using your chosen engine, simplifying the process of generating dynamic HTML.

    What are template literals in JavaScript and how do they relate to templating engines?

    Template literals are a feature in JavaScript that allows for easier string interpolation and multi-line strings. While they can be used to generate HTML, they lack many of the features provided by templating engines, such as support for reusable components and separation of concerns. However, they can be useful for simple use cases where a full-fledged templating engine is not necessary.

    How do I choose the right JavaScript templating engine for my project?

    Choosing the right templating engine depends on your project requirements and personal preferences. Consider factors such as the complexity of your project, the learning curve of the engine, and the features it offers. It’s also a good idea to look at the community and support around the engine.

    Are there any performance differences between JavaScript templating engines?

    Yes, there can be significant performance differences between different templating engines. Some engines are faster at compiling templates, while others excel at rendering. However, for most web applications, these differences are unlikely to have a noticeable impact on performance.

    Can I create my own JavaScript templating engine?

    Yes, it’s possible to create your own templating engine, although it’s generally not recommended unless you have specific needs that aren’t met by existing engines. Creating a templating engine requires a deep understanding of JavaScript and can be time-consuming.

    How do I debug issues with a JavaScript templating engine?

    Debugging issues with a templating engine can be challenging, as errors often occur at runtime. However, most engines provide helpful error messages that can guide you towards the source of the problem. It’s also a good idea to use a linter to catch syntax errors.

    Are JavaScript templating engines only used for web development?

    While templating engines are most commonly used in web development, they can also be used in other contexts. For example, they can be used to generate emails, PDFs, or any other type of text-based content. The key advantage of templating engines is their ability to separate data from presentation, which can be useful in a wide range of applications.

The above is the detailed content of An Overview of JavaScript Templating Engines. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template