Rendering with ejs in express.js

When rendering a template in express.js. there are many options to choose from, however so far I seem to prefer Embedded javaScript or EJS for short. I have written a post on using the ejs module by itself in node.js, however this post is more about using it in an express.js environment. As Such I will be covering how to set up a renderer with ejs.

Basic example

To get started with a basic example start a new project folder, install express, and ejs. In this post I am using express 4.16.x, and ejs 2.6.x. In no major code breaking changes have happened this post should still be up to date.

1
2
3
4
5
6
$ mkdir render-ejs
$ cd render-ejs
$ npm init
$ npm install express@4.16.3 --save
$ npm install ejs@2.6.1 --save
$ mkdir views

The views folder

As you may have noticed I made a views folder inside the root name space of the project folder, this is where I will be placing all my ejs template files. For my basic demo I just stared off with a single index.ejs file in the root name space of the views folder.

index.ejs would look like this for starters:

1
<h1>Hello ejs!</h1>

The app.js for the basic example

The main file that is called to start the project is often called app.js in an express.js project, often located at the root of the project folder. In this basic example of using ejs to render a template using express.js and node.js, I just need to set the views path to the folder where my ejs template are, and set the view engine to ejs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let express = require('express'),
path = require('path'),
app = express(),
// getting port this way
port = process.env.PORT || process.argv[2] || 8080;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
res.render('index',{});
});
app.listen(port, function () {
console.log('app is up on port: ' + port);
});

Conclusion

When I start this and go to localhost:8080 in my browser I am greeted with the “Hello ejs!” message. I have another post on ejs in which I work with the ejs module by itself, which might be a good idea to do if you want to learn more about ejs.