Express + Handlebars: Rendering a JavaScript array with a loop

Updated: January 18, 2024 By: Guest Contributor Post a comment

Introduction

Creating dynamic web applications often involves rendering data on the front end that’s stored in the back end. Express, a web application framework for Node.js, together with Handlebars, a powerful templating engine, make it seamless to render JavaScript arrays and objects in the browser. In this tutorial, we’ll go through the process of setting up Express with Handlebars and explain how to iterate over JavaScript arrays to dynamically generate HTML content.

Setting Up Express

Before diving into Handlebars and array rendering, we need to set up an Express application. Begin by initializing a new Node.js project, if you haven’t already:

mkdir my-express-app
cd my-express-app
npm init -y
npm install express

Next, create an `app.js` file as your main application file:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Your basic Express application is now ready. To start your server, run node app.js.

Integrating Handlebars

Handlebars allows us to create templates with dynamic content that can change depending on the data provided. To integrate Handlebars into your Express application, install the `express-handlebars` package:

npm install express-handlebars

Next, configure Handlebars as the view engine for Express:

const express = require('express');
const { engine } = require('express-handlebars');

const app = express();
const port = 3000;

app.engine('handlebars', engine());
app.set('view engine', 'handlebars');

// ... existing code

Create a `views` directory in your project, where you’ll store all handlebars templates with the `.handlebars` file extension. For example, you could create a `views/home.handlebars` file for your homepage.

Rendering a JavaScript Array in Handlebars

Let’s say you have a JavaScript array that you want to render on your web page. First, you’ll need to pass this array to your Handlebars template from the Express route.

// inside app.js
app.get('/', (req, res) => {
  const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
  res.render('home', { fruits: fruits });
});

In your `home.handlebars` template, you can then use the Handlebars each helper to loop through the array and render its items:

<ul>
  {{#each fruits}}
  <li>{{this}}</li>
  {{/each}}
</ul>

When you navigate to the home route, Handlebars processes the `home.handlebars` template, iterating over each element in the `fruits` array and rendering an `<li>` element for it. The outcome is a dynamically generated unordered list of fruit names.

Advanced Array Rendering

Often, the array you want to render is more complex, containing objects instead of simple strings. Assume you have the following array of fruit objects, each with a `name` and `color`:

const fruits = [
  { name: 'Apple', color: 'Red' },
  { name: 'Banana', color: 'Yellow' },
  // ... more fruits
];

You can access the properties of the objects within the `each` loop like this:

<ul>
  {{#each fruits}}
  <li>{{name}} is {{color}}.</li>
  {{/each}}
</ul>

The template engine parses the placeholders and replaces them with the corresponding values from the objects in the array. In this case, it creates an unordered list describing each fruit and its color.

Concluding Thoughts

Using Handlebars with Express makes it simple to render dynamic content such as JavaScript arrays in your web applications. With the power of Handlebars templates and Express routes, you are equipped to create engaging, data-driven interfaces. Be sure to delve deeper into the robust features offered by both technologies, such as partials and helpers in Handlebars, to further enhance your web development skills.

This tutorial provides a foundation for using Express and Handlebars to render arrays in your web projects. Play around with the code examples, experiment with different types of data, and see how you can customize the rendering process to fit the needs of your unique application.