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>
//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</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>
//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</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>
//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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

JavaScript array built-in methods such as .map(), .filter() and .reduce() can simplify data processing; 1) .map() is used to convert elements one to one to generate new arrays; 2) .filter() is used to filter elements by condition; 3) .reduce() is used to aggregate data as a single value; misuse should be avoided when used, resulting in side effects or performance problems.

JavaScript's event loop manages asynchronous operations by coordinating call stacks, WebAPIs, and task queues. 1. The call stack executes synchronous code, and when encountering asynchronous tasks, it is handed over to WebAPI for processing; 2. After the WebAPI completes the task in the background, it puts the callback into the corresponding queue (macro task or micro task); 3. The event loop checks whether the call stack is empty. If it is empty, the callback is taken out from the queue and pushed into the call stack for execution; 4. Micro tasks (such as Promise.then) take precedence over macro tasks (such as setTimeout); 5. Understanding the event loop helps to avoid blocking the main thread and optimize the code execution order.
