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
- This class we talked about template setup using handlebars
- handlebars is the View part of MVC
- We can add handlebars view element using the handlebars package
npm install express-handlebars
- Why we use handlebars and other templating engine -
- Prevents attacks like XSS by having the server and clinet in the same origin.
- Helps us to dynamically generate content (by passing data to the template from the backend)
- Helps us to repeat ourselves less (main problem with normal HTML) (reusability)
- Helps us to keep the client and server side logic in one code hence making it easier to debug
- We can initialize the handlebars using the following lines
app.set("view engine", 'handlebars')
app.set("views", viewsPath)
app.engine('handlebars', handlebars.engine())
- After initializing we can use the handlebars pages in the views directory referencing the
main.handlebars
layout. - We can use the render function to render these view engine based pages.
- We can pass data to these pages easily using javascript objects after the view name in the render function.
- We can use a static folder to host static resources like images, css files and etc.
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"
}
}