This tutorial was originally written for express v4.17.1 and ejs v3.1.5. It has been verified with Node v16.0.0, npm v7.11.1, express v4.17.1, and ejs v3.1.6.
Step 1 — Setting Up the Project
First, open your terminal window and create a new project directory:
mkdir ejs-demo
Copy
Then, navigate to the newly created directory:
cd ejs-demo
Copy
At this point, you can initialize a new npm project:
npm init -y
Copy
Next, you will need to install the express package:
npm install express@4.17.1
Copy
Then install the ejs package:
npm install ejs@3.1.6
Copy
At this point, you have a new project ready to use Express and EJS.
Step 1 — Configuring with server.js
With all of the dependencies installed, let’s configure the application to use EJS and set up the routes for the Index page and the About page.
Create a new server.js file and open it with your code editor and add the following lines of code:
server.js
var express = require('express');
var app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
// use res.render to load up an ejs view file
// index page
app.get('/', function(req, res) {
res.render('pages/index');
});
// about page
app.get('/about', function(req, res) {
res.render('pages/about');
});
app.listen(8080);
console.log('Server is listening on port 8080');
Copy
This code defines the application and listens on port 8080.
This code also sets EJS as the view engine for the Express application using:
`app.set('view engine', 'ejs');`
Copy
Notice how the code sends a view to the user by using res.render(). It is important to note that res.render() will look in a views folder for the view. So you only have to define pages/index since the full path is views/pages/index.
Next, you will create the views using EJS.
Step 2 — Creating the EJS Partials
Like a lot of the applications you build, there will be a lot of code that is reused. These are considered partials. In this example, there will be three partials that will be reused on the Index page and About page: head.ejs, header.ejs, and footer.ejs. Let’s make those files now.
Create a new views directory:
mkdir views
Copy
Then, create a new partials subdirectory:
mkdir views/partials
Copy
In this directory, create a new head.ejs file and open it with your code editor. Add the following lines of code: