How to use handlebars template engine in your nodeJs App

Introduction

Usually nodejs interact with client side using React, Angular. These technologies are mainly used for bigger projects. But what If we have to create small and simple project using nodeJs and ExpressJs. In order to solve this problem we have template engines to create simple web application. Template engines are used when we need to build rapidly web applications which is split into different components. There are numerous template engines available. Few popular template engines are

  • Ejs : Embeded javascript
  • Pug
  • hbs: Handlebars
  • Express-handlebars
  • Sprightly

In this tutorial blog we will learn how to use hbs (handlebars) to create web app with nodejs and expressjs. Handlebars.js is a popular templating engine that is powerful, simple to use and has a large community. It is based on Mustache and Handlebars provides the power necessary to let you build semantic templates effectively with no frustration. Express supports the view engine through the app.set function, which sets the view engine property of your application to the template engine you want to use. With Handlebars.js, you'll be able to build semantic templates effectively with no frustration.

Pre-requisite

Before starting with this tutorial blog you must have a basic knowledge working with Nodejs and ExpressJs and also you need node package manager which comes with downloading nodejs in your computer. To write code you need one IDE (Integrated Development Environment). If you don't have have above mentioned things, you can download it from the given links below.

Setting Up the Environment

  1. Create a folder named learnhbs and open it with vscode editor. Initialize npm which will create a package.json file which manage all the dependencies. Open vs code terminal and type
$ npm init -y
  1. Now install expressjs and hbs by typing
$ npm install express hbs

Till now you have a node_modules folder and two files package.json and package-lock.json

Configuring with Expressjs server

Create a server.js file and write the following lines of code

const express = require('express');
//Creating an app from express
const app = express();

//Setting veiw engine
app.set('view engine','hbs');

//Creating routes
//Home Page
app.get('/', (req,res)=>{
    res.send('Hellow world');
})

//listening to the server
app.listen(5000,()=>{
    console.log(`Server is listening at 5000`);
})

Run the server.js file and open localhost:5000 in the browser, you will be having the result

hellowrodlresult.png

Express supports the view engine through the app.set function, which sets the view engine property of your application to the template engine you want to use.

//Setting veiw engine
app.set('view engine','hbs');
//This code creates sets template engine to hbs

Starting with handlebars template engine

Create a folder named views. Inside this create one more folder named pages and inside it create three pages index.hbs, about.hbs, and contact.hbs.

- Any template engine looks for files only in views directory, however you can explicitly set to different folder name by adding following code

app.set('views','templatefiles');

- Extensions of theviews file should be hbs only, or the template engine you are using like ejs.

- res.render('file path') used to render template files.

Now change the code in the server.js file to

const express = require('express');
//Creating an app from express
const app = express();

//Setting veiw engine
app.set('view engine','hbs');

//Creating routes
//Home Page
app.get('/', (req,res)=>{
    res.render('pages/index');
})
//About page
app.get('/about',(req,res)=>{
    res.render('pages/about')
})
//Contact page page
app.get('/about',(req,res)=>{
    res.render('pages/contact')
})


//listening to the server
app.listen(5000,()=>{
    console.log(`Server is listening at 5000`);
})

Add following code to the hbs files

index.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Templating hbs with express</title>
</head>
<body>
    <h1>I am template engine home</h1> 
</body>
</html>

about.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Templating hbs with express</title>
</head>
<body>
    <h1>I am template engine about</h1> 
</body>
</html>

contact.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Templating hbs with express</title>
</head>
<body>
    <h1>I am template engine contact</h1> 
</body>
</html>

Now you can see that the head tag is repeating in all files. There will be a lot of repeating code in the project. To prevent the repeating code, template engine provides us with partials which can be reused on everywhere it is needed.

Setting the partials

In this section we will be discussing partials. Partials are reusable templates that can be used to separate your code into logical sections. Partials help you reduce repetition as well as modularize code by allowing you to break it down into smaller, reusable blocks of content or functionality. You can think of them as mini-templates that you can reuse throughout your application’s pages or components.

Using partials is one way we can quickly build up our HTML template with minimal effort by reusing existing elements from other templates and only adding the unique elements for each page we are building (in our case, index, about and contact).

Create a folder named partials inside views directory. Inside partials create all the repeatable code files like head.hbs, footer.hbs, header.hbs etc. Add the repeatable codes to the respective files.

head.hbs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Templating hbs with express</title>
</head>

header.hbs

<h3 style="background-color: rgb(110, 109, 109); color:aliceblue;text-align:center;">
     I am header
</h3>

Footer.hbs

<footer
  style="background-color: rgb(36, 30, 30); color:white; text-align:center">
    @copyright reserved to template engine | Footer
</footer>

To re-use these partials in pages we need to register the partials in server.js file.

//Require hbs before stting up the view engine
const hbs = require('hbs');

//Register partials below setting upp the view engine
hbs.registerPartials('./views/partials');

Now change the pages code to ,

home.hbs

{{> head}}
<body>
    {{>header}}
    <h1>I am template engine home</h1> 
    {{>footer}}
</body>
</html>

- {{ }} This brackets is used to write javascript logic in handlebars.

- {{> }} greater-than sign tells views to render partials.

about.hbs

{{> head}}
<body>
    {{>header}}
    <h1>I am template engine about</h1> 
    {{>footer}}
</body>
</html>

contact.hbs

{{> head}}
<body>
    {{>header}}
    <h1>I am template engine contact</h1> 
    {{>footer}}
</body>
</html>

Passing dynamic data to the pages from server

Paasing dynamic content to the views is so easy in handlebars.

  1. Add second parameter as an object to the res.render function and pass whatever data you want, like
app.get('/', (req,res)=>{
    res.render('pages/index',{
        title:'I am title' //passing title here
    });
})
  1. To access dynamic data on the pages, add the following code to handlebars files.
<h1>I am template engine home {{title}}</h1>

Iterating through the list in handlebars

  1. Pass the list through res.render function
app.get('/', (req,res)=>{
    const names = ['name1','name2','name3','name4'];
    res.render('pages/index',{
        title:'I am title',
        names:names
    });
})
  1. To iterate through the list, add the following codes in handlebars files
<ul class="people_list">
  {{#each names}}
    <li>{{this}}</li>
  {{/each}}
</ul>
  • > The each-helper iterates an array, allowing you to access the properties of each object via simple handlebars expressions. this keyword refers to the current object.

Conclusion

In this tutorail blog I ahve tried my best to explain how to use handlebars template engine with expressjs server and create a mini project. I hope you find this article informative and it helps you to create a small application using handlebars and expressJs.

Did you find this article valuable?

Support ghulamrabbani by becoming a sponsor. Any amount is appreciated!