Trusted answers to developer questions

What are Handlebars in JavaScript?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Handlebars is a template engine that can generate HTML using JavaScript code. The template engine is very easy to learn and use due to its syntax and the built-in helpers it provides. Handlebars can be included in a project using the CDN link in the <script> tag:

<script
src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.1.2/handlebars.min.js">
</script>

To get a link for the latest Handlebars version, visit cdnjs.com.

Creating and executing a simple template

  1. Declare a template in the HTML file. Handlebars expressions are put into double curly braces {{expr}} for HTML-escaped content; otherwise, use triple curly brackets {{{expr}}} to avoid HTML-escaping.

In the JavaScript file:

  1. Get this template using document.getElementById().
  2. Compile it using Handlebars.compile().
  3. Since a template is meaningless without a context, an object containing the required variables is created. This data is known as the ​context.
  4. Generate the HTML with template(context).
  5. Insert the generated HTML into​ an HTML element.
svg viewer

Helpers

Handlebars have built-in helpers for common tasks, such as if or else condition blocks. The name of the helper is preceded by a # in the starting tag, and by a / in the closing tag – instead of using <> for tags, curly braces are used.

#if helper

The #if helper takes in one argument and renders the HTML inside the helper block if the passed parameter is not: false, undefined, null, "", [] or 0; otherwise, the {{else}} block executes.

The {{else}} tag is written inside the #if helper; it does not require a closing tag.

#each helper

The #each helper is used to iterate over a list, which is passed as the argument. Each item of the list, as well as its attributes, can be accessed using the this keyword.

The code below demonstrates how to use #if, {{else}}, and #each.

RELATED TAGS

handlebars
javascript
html
template
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?