5.4 Rendering Templates with Data

View Engine: HandleBar
Website: https://handlebarsjs.com/
Package: https://www.npmjs.com/package/hbs


Install HBS
npm install hbs --save


Setup HBS in Express

app.set('view engine', 'hbs')


Views Dir
Create a directory called views.
Then, inside views, create about.hbs.
In this case, we just copy some html in.


Render View

app.get('/about', (request, response)=>{
response.render('about.hbs');
});

Dynamic Binding
Injecting Data

app.get('/about', (request, response)=>{
response.render('about.hbs', {
pageTitle: "About Page",
currentyear: new Date().getFullYear()
});
});

Using Data

{{pageTitle}} will be replaced by About Page

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{pageTitle}}</title>
</head>
<body>
<h1>{{pageTitle}}</h1>
<p>Some text here</p>
<footer>
<p>Copyright {{currentYear}}</p>
</footer>
</body>
</html>