Using Handlebars Template Engine in Express

Learn how to use the Handlebars template engine in Express to render dynamic HTML pages.

Now that we have an idea about the basics of Express routing and setup, let’s build a two-page application that handles a user login form. Along the way, we will learn about how Express renders application HTML pages, how they can be combined with a generic layout page, and how to serve static files such as CSS and icons. We will also discuss how to handle form input and how to use session data.

Express templating

Our current route handlers are returning simple messages to the browser. In a real-world application, however, we will need to render complete HTML pages with a standard HTML structure, including links to CSS stylesheets if necessary and a header section. Express uses a template engine that allows us to specify the HTML we need for each page and also provides the mechanism of injecting runtime values into these templates, similar to the template mechanisms of Angular, React, or Vue.

Express supports many different templating engines, including Pug, Mustache, Jade, Dust, and many more. Introducing a template engine into our Express application is a matter of installing the engine of choice via npm and configuring Express to use it.

In this application, we will use the Handlebars template engine. Handlebars uses standard HTML snippets, along with substitution variables using a double brace syntax, in order to inject values into our HTML. This is similar to what we have seen with our SPA frameworks. Some template engines, such as Pug and Jade, use their own custom formats to represent HTML elements and are a mix of HTML keywords, class names, and variable substitution formats. As a quick comparison, consider a Handlebars template as follows:

Get hands-on with 1200+ tech skills courses.