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
{{expr}}
for HTML-escaped content; otherwise, use triple curly brackets {{{expr}}}
to avoid HTML-escaping.In the JavaScript file:
document.getElementById()
.Handlebars.compile()
.template(context)
.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.
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.
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
.
Free Resources