How To Use Handlebars in Node JS

Posted By : Hotam Singh | 24-Sep-2017

 

In this article, we will be discussing how to use handlebars.js templating engine into our node.js application. I have given the brief introduction about handlebars in my previous blog “Introduction To Handlebars”.

 

So let’s get started with using handlebars in the node.js application. First, we need to create a server that will handle client requests. We can create a server in node.js using express(A framework in node.js which is used to create web application).

 

Consider the following code that will create a server and listens on specified port :

Now start using handlebars. First we need to require “express-handlebars” module as:

This will include “express-handlebars” module into our application.

 

Next step is to setup view engine.

Line no. 7 in above image will set up default “views” directory that view engine will look the files to be rendered.

Line no. 8 defines the view engine and setup default configuration for handlebars view engine.

Line no. 9 setups “hbs” as a view engine.

 

Next step is to create “views” directory and create another directory “layouts” inside “views” directory and create a file “layout.hbs” and put following code inside this file.

At Line no. 7, {{{ body }}} will append the whole body once our server renders any file keeping the head section same.

 

Now create another file “users.hbs” that will display user’s name, mob_no, email etc once a client request “/users”  request. Include the following code in users.hbs file. Save this file inside “views” directory.

This body will append in the layout.hbs file where we used {{{ body }}} we created just before this file.

I have used two helpers {{#if }} and {{#each }}. {{#if }} helper will execute if we pass users(an array) list from the server.

{{#each }} helper will read each value on index base and these values will be shown in a table.

 

Now modify our get request “/” to “/users” to render user’s list on the browser.

We will send a hardcoded user’s list that will be displayed on the browser. res.render() will render users.hbs file we created inside “views” directory.

 

About Author

Author Image
Hotam Singh

Hotam has 1.5 years of experience in Node.JS. He has worked on Front End, JavaScript, Jquery, Backbone.JS, Database: MySQL, MongoDB. His hobbies are playing Sudoku/Puzzles and watching movies.

Request for Proposal

Name is required

Comment is required

Sending message..