search
HomeWeb Front-endJS TutorialAn Overview of JavaScript Templating Engines

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> id<span >="template"</script></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></span>></span>
</span>
//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

    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> id<span >="template"</script></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></span>></span>
    </span>
    //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 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> id<span >="template"</script></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></span>></span></span>
    //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 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
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment