In this tutorial, we will learn how to pass data from an Express server to templates. This allows for dynamic content, meaning our web page can change based on the data it receives. By the end of this tutorial, you will be able to:
This tutorial assumes a basic understanding of JavaScript and familiarity with Node.js and Express.js.
Express.js uses a feature called template engines to generate HTML with dynamic content. One popular choice is EJS (Embedded JavaScript), but others like Pug, Handlebars, and Mustache can also be used. When using a template engine, we can provide a data object from our server to the template. The template engine will then replace placeholders in our HTML with the actual data.
To pass data to templates in Express.js, you need to follow these steps:
Let's see an example using the EJS template engine.
First, install EJS with npm install ejs
.
Then, in your server file, set EJS as the template engine:
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
Now, let's define a route that passes data to a template:
app.get('/', (req, res) => {
const data = {
title: 'Home',
message: 'Welcome to our website!'
};
res.render('index', data);
});
Here, res.render('index', data);
tells Express to render the 'index' view with the provided 'data' object.
This data can be accessed in our index.ejs
file:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= message %></h1>
</body>
</html>
In this EJS file, <%= title %>
and <%= message %>
are placeholders that get replaced with the values of 'title' and 'message' from our data object.
When you access the '/' route, you should see a page with the title 'Home' and a heading saying 'Welcome to our website!'.
In this tutorial, we've learned how to pass data from an Express server to a template, allowing for dynamic content. We've seen how to set up a template engine, define a data object, pass it to a template, and use the data in the template.
Next, you can learn more about other template engines, or how to fetch and pass data from a database.
Remember to install and set up a template engine, define and pass your data, and use the data in your templates. Happy coding!