Express + Handlebars: Passing variables back and forth

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

Introduction

Handlebars is a popular templating engine that can be integrated with Express, a Node.js web application framework. When developing web applications, a common task is passing data from the server to the client and vice versa. This tutorial will cover the essentials of transferring variables between Express and Handlebars templates, enhancing the interactivity of your web pages.

Getting Started with Express and Handlebars

Before diving into data passing, ensure Node.js is installed. Then, set up a new Express project and install the required packages:

$ mkdir express-handlebars-demo
$ cd express-handlebars-demo
$ npm init -y
$ npm install express express-handlebars body-parser

Here’s a simple server setup:

const express = require('express');
const exphbs  = require('express-handlebars');
const bodyParser = require('body-parser');

const app = express();

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

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/', (req, res) => {
    res.render('home');
});

app.listen(3000, () => {
    console.log('The web server has started on port 3000');
});

Passing Variables from Express to Handlebars

To pass data from Express to a Handlebars template, include an object as the second argument to the render method:

app.get('/', (req, res) => {
    res.render('home', {
        user: 'John Doe',
        age: 30
    });
});

In your Handlebars template, you can then use the passed variables:

{{! home.handlebars template }}
<h1>Welcome, {{user}}!</h1>
<p>You are {{age}} years old.</p>

Forms and POST Requests

To collect user input, forms are used with POST requests:

{{! home.handlebars template }}
<form method="POST" action="/submit">
  <input type="text" name="username">
  <input type="submit" value="Submit">
</form>

Handle the submission on the server:

app.post('/submit', (req, res) => {
    const username = req.body.username;
    res.render('response', {
        username: username
    });
});

Query Parameters and GET Requests

GET requests can carry data via query parameters. Handle this in Express and send the data to Handlebars:

app.get('/user', (req, res) => {
    const name = req.query.name;
    res.render('user', { name: name });
});

Accessing the data in the Handlebars template is straightforward:

{{! user.handlebars template }}
<p>Hello, {{name}}!</p>

Using Partials

Handlebars partials allow the reuse of common template parts:

{{! partials/header.handlebars }}
<header><h1>My Website</h1></header>

// Registering partials
app.engine('handlebars', exphbs({
    defaultLayout: 'main',
    partialsDir: __dirname + '/views/partials/'
}));

Using a partial in a template:

{{! home.handlebars template }}
{{> header}}
...
{{/user}}
// Note the user block is rendered where the {{/user}} call is.

Passing Variables from Handlebars to Express

Passing variables back to Express from a template is done with forms or AJAX requests. For example, here’s how to capture data with AJAX:


<script>
function submitData() {
  const data = {
    user: document.getElementById('user').value,
  };

  fetch('/api/data', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  })
  .then(response => response.json())
  .then(data => console.log(data));
}
</script>

On the Express side, receive and use the data:

app.post('/api/data', (req, res) => {
  console.log('Data received:', req.body);
  res.json({ status: 'success', data: req.body });
});

Conclusion

This brief walkthrough covers the basic interactions between an Express server and Handlebars templates. By mastering the flow of data between the client and server, you can create dynamic and responsive web applications that engage users effectively.

As an additional resource, consider looking at the documentation for Express and Handlebars to better understand available features that can augment your application’s functionality.

Remember, practice makes perfect, so keep experimenting and developing your skills!