Introduction
When building web applications, rendering data in a structured and user-friendly manner is a common requirement. In this tutorial, we will learn how to leverage Express.js and Handlebars to render a dynamic data table from an array. Express.js will serve as our web framework, while Handlebars will enable us to use templates that can create HTML with injected data.
Setting Up
Before jumping into code, ensure you have Node.js
installed. Create a new project directory, initialize a new npm
project, and install the required packages:
$ mkdir express-handlebars-table
$ cd express-handlebars-table
$ npm init -y
$ npm install express express-handlebars
Project Structure
Let’s define a basic project structure:
- app.js – Our main server file
- views/layouts/main.handlebars – The main layout
- views/table.handlebars – A view to render our table
Configuring Express and Handlebars
In app.js, set up Express and configure Handlebars as your view engine:
const express = require('express');
const { engine } = require('express-handlebars');
const app = express();
app.engine('handlebars', engine());
app.set('view engine', 'handlebars');
app.set('views', './views');
Creating a Layout
Create a main.handlebars
file in the views/layouts
directory. This file will serve as the layout for all your views.
<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
</head>
<body>
{{{body}}}
</body>
</html>
Rendering the Table
Create table.handlebars
inside the views
directory:
<h1>{{title}}</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
{{#each people}}
<tr>
<td>{{this.id}}</td>
<td>{{this.name}}</td>
<td>{{this.age}}</td>
</tr>
{{/each}}
</tbody>
</table>
Serving the Data
In your app.js
, beneath the app configuration, define a route to render your table view with data:
app.get('/table', (req, res) => {
const data = {
title: 'People List',
people: [
{ id: 1, name: 'John Doe', age: 30 },
// ... more people
]
};
res.render('table', data);
});
Styling the Table
You might want to add styles to your table. You can include a <style>
tag in the main.handlebars
layout or link an external CSS file:
<link rel="stylesheet" href="/stylesheets/style.css">
Running the Server
Back in your terminal, start the server:
$ node app.js
Open your browser and navigate to http://localhost:3000/table
to see your rendered data table.
Conclusion
This tutorial introduced you to rendering data tables in an Express.js application with Handlebars templating. Play around with the data and templates to fully grasp the flexibility Handlebars offers for server-side rendering.