Express.js - Looping through data (hbs template)
In Express, when using Handlebars (hbs) as templating engine, we can create looping by the {{#each}} block helper. The {{#each}} helper is used to iterate over arrays or objects in templates.
Passing Data to the Template
index.js// User Data
const users = [
{ name: 'Ram Kumar', age: 30 },
{ name: 'Ramesh', age: 25 },
{ name: 'Sam', age: 22 },
{ name: 'Suresh', age: 34 },
];
// Define a route and pass an array of data
app.get('/', (req, res) => {
res.render('index', {
title: 'List of Users',
users: users
});
});
Create the Handlebars Template
views/index.hbs<html> <head> </head> <body> <h1>{{title}}</h1> <ul> {{#each users}} <li>{{name}} - Age: {{age}}</li> {{/each}} </ul> </body> </html>
Run the Server
Run the server using the command is given below.
node index.js
D:\my-app>node index.js Server is running on http://localhost:5000