Content
Introduction
In this post I will demonstrate how to use the Handlebars view engine with Express.
Requirements
Node.js has to be installed on your system.
Express
Express is a simple and easy-to-use Node.js-Framework. It is very flexible and comes with a lot of features for building web and mobile applications.
Handlebars
Handlebars is an extension for the popular Mustache template language. It is logic-less and keeps the views and logic separated.
Set up Express
Create a directory for your application and make it your working directory.
After that you have to create a package.json file interactively.
This command will ask you a bunch of questions. Hit return to proceed using default values.
Install Express and add it to the dependencies list.
Create an index.js in the root of your project and add the following content:
Start the server and visit http://localhost:3000. The output will be Hello World!.
Install and use Handlebars
Install the express-handlebars package via npm.
Afterwards, update the index.js as follows:
When requesting the index route (”/”), the application tries to render the index.handlebars which has to be present in a “views” folder. To make the code work, create the directory and the file. Then put in “Rendered by Handlebars, AWESOME!”. After restarting the server and calling the index route, you should see the sentence in your browser.
Main layout
A layout file is a simple Handlebars template which contains a {{{body}}} placeholder and serves as an HTML wrapper for views. To specify such a layout, we have to slightly adjust the code.
After these changes the application searches for a main.handlebars layout file in “views/layouts”. Accordingly, the layout folder and main.handlebars file have to be created.
main.handlebars example:
Do not forget to restart the server after adjusting the code.
Change file extension
You want to use .hbs file extension instead of .handlebars? No problem!