Using Templates in benhall/express-demo


In your Express application built using benhall/express-demo, you may encounter a requirement to render dynamic HTML content. In such a scenario, you can make use of templates and a template engine to generate and serve the desired HTML content.


  1. Create a new template file: First, create a new template file in the views directory of your project. For this example, let's name it welcome.hbs.

  2. Define the logic: Open the newly created welcome.hbs file and define the logic for your template. For instance, you may want to display a welcome message with the user's name. In that case, you can define the following content:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <h1>Welcome, <strong>{{ name }}</strong></h1>

In the above example, {{ name }} is a placeholder for the dynamic value that will be replaced with the actual user's name when the template is rendered.

  1. Use the template engine to render the content: To use this template in your Express application, you need to make use of a template engine like Handlebars.js. First, install Handlebars.js as a dependency by adding the following line to your package.json file:
"handlebars": "^4.7.6"

Then, require Handlebars.js in your app.js file:

const express = require('express');
const handlebars = require('handlebars');
const exphbs = require('express-handlebars');

// ...

const app = express();

// Configure Handlebars.js as the template engine
const hbs = exphbs.create({
  extname: 'hbs',
  defaultLayout: 'layout.hbs',
  layoutsDir: 'views/layouts',
  partialsDir: 'views/partials',
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');

// ...

Now, you can create a new route that renders the welcome.hbs template:

app.get('/welcome', (req, res) => {
  const context = { name: || 'Stranger' };
  res.render('welcome', context);


To verify the solution, you can create tests using a testing framework like Mocha and Chai. Here's an example of how you can test the /welcome route:

const request = require('supertest')(app);

describe('GET /welcome', () => {
  it('should render the welcome template with a default name', (done) => {
      .expect('Content-Type', /html/)
      .expect((res) => {
        expect(res.text).to.include('Welcome, Stranger');

  it('should render the welcome template with a provided name', (done) => {
      .expect('Content-Type', /html/)
      .expect((res) => {
        expect(res.text).to.include('Welcome, John');

These tests cover the two scenarios: rendering the welcome template with the default name and rendering it with a provided name.