How to Setup Handlebars View Engine in Node.js ?

Handlebars is a template engine that is widely used and easy to use. The pages contain .hbs extension and there are many other template engines in the market like EJS, Mustache, etc.

Installation of hbs module:

  1. You can visit the link Install hbs module. You can install this package by using this command.
    npm install hbs
  2. After installing hbs module, you can check your hbs version in command prompt using the command.
    npm version hbs
  3. After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.
    node index.js
  4. To setup hbs view engine, you need to write this middleware in your index.js as follow:
    app.set('views', path.join(__dirname))
    app.set('view engine', 'hbs')
  5. Now create the file and run the code. It will display the result.

Filename: Home.hbs

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<head>
    <title>Handlebars Demo</title>
</head>
<body>
  
    <!-- For loop demo -->
    {{#each array}} 
      <h4>{{this}}</h4>
    {{/each}}
    <h4>{{message}}</h4>
</body>
</html>

chevron_right


Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

const express = require('express')
const path = require('path')
const hbs = require('hbs')
const app = express()
  
// View Engine Setup
app.set('views', path.join(__dirname))
app.set('view engine', 'hbs')
  
app.get('/', function(req, res){
    res.render('Home', {
       array: ['One', 'Two', 'Three', 'Four'],
       message: 'Greetings from geekforgeeks'
    })
})
  
app.listen(8080, function(error){
    if(error) throw error
    console.log("Server created Successfully")
})

chevron_right


Steps to run the program:

  1. The project structure will look like this:
  2. Make sure you have installed hbs and express module using the following commands:
    npm install hbs
    npm install express
  3. Run index.js file using the following command:
    node index.js

    Output of above command

  4. Open browser and type this URL: http://localhost:8080/. Then you will see the Home.hbs page as shown below:
    HBS page demo

So this is how you can setup Handlebars (hbs) view engine in node.js. There are many other handlebars engines exist like EJS, Mustache, etc.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.