Go back

Introduction to handlebars

What is handlebars?

Handlebars is a tool we can use with express to inject data from server side.

Handlebars handle the view part of a website.

Handlebars and templating

app.set("view engine", 'handlebars')
app.set("views", viewsPath)
app.engine('handlebars', handlebars.engine())
app.use(express.static("./static"))

Reading Resources

Guide to handlebars js - https://handlebarsjs.com/guide/

Codes

app.js

const express = require("express")
const app = express()

const PORT = 3000

app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`)
})

const handlebars = require('express-handlebars')
const path = require('path')

const viewsPath = path.join(__dirname, "views")
app.use(express.static("./static"))

app.set("view engine", 'handlebars')
app.set("views", viewsPath)
app.engine('handlebars', handlebars.engine())

app.get("/:name", (req,res) => {
    const { name } = req.params
    res.render("index", {
        name,
        title: "Welcome"
    })
})

app.get("/index2", (req,res) => {
    res.render("index2")
})

views/layouts/main.handlebars

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{page.title ? page.title : "Document"}}</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <nav>Our cool application</nav>
    {{{body}}}
</body>
</html>

views/index.handlebars

<h1>Hello {{name}}</h1>

views/index2.handlebars

<h1>Hello World 2!</h1>

package.json

Installed packages are - express, express-handlebars, handlebars

{
  "name": "day_13",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "express": "^4.21.1",
    "express-handlebars": "^8.0.1",
    "handlebars": "^4.7.8"
  },
  "devDependencies": {
    "nodemon": "^3.1.7"
  }
}