Scenario:
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.
Solution:
Create a new template file: First, create a new template file in the
views
directory of your project. For this example, let’s name itwelcome.hbs
.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">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<h1>Welcome, <strong>{{ name }}</strong></h1>
</body>
</html>
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.
- 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: req.query.name || 'Stranger' };
res.render('welcome', context);
});
Tests:
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) => {
request.get('/welcome')
.expect('Content-Type', /html/)
.expect(200)
.expect((res) => {
expect(res.text).to.include('Welcome, Stranger');
})
.end(done);
});
it('should render the welcome template with a provided name', (done) => {
request.get('/welcome?name=John')
.expect('Content-Type', /html/)
.expect(200)
.expect((res) => {
expect(res.text).to.include('Welcome, John');
})
.end(done);
});
});
These tests cover the two scenarios: rendering the welcome template with the default name and rendering it with a provided name.