How to use the EJS view engine on Node.js

NSerus
2 min readMar 24, 2021

EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. No religiousness about how to organize things. No reinvention of iteration and control-flow. It’s just plain JavaScript.

Taken from https://ejs.co/

As we can see, EJS is a tool that lets us use HTML code on our Node,js program, we are going to make a little example showing how EJS interacts on the Node.js environment.

It’s supposed that Node.js is already installed on the computer before this tutorial.

Dependencies and Building the Environment

So, after creating the directory and opening a terminal in that location we initiate the project with:

npm init

After this we need to install our dependencies, the first one being express (already explained Express.js in another tutorial):

npm install express -save

And the last dependency is obviously EJS, the star of today:

npm install ejs -save

Now that we finished installing the dependencies we need to make directories (of course, this is only for organization/good practice purposes) and create an ejs file.

Created directory with EJS file

With all of the structure of the program ready, we are now ready to code.

Coding

The difference in programing with EJS is that now we need to set the view engine for the EJS files to open properly using the following line of code:

app.set(‘view engine’, ‘ejs’)

Now after setting the rendering engine, we dont need to indicate the extension of the file when opening.

After having this knowledge, we can code app.js to get the .ejs file when requested.

var express = require('express');  var app = express();
app.set('view engine', 'ejs'); //settig the render process

app.get('/registo',function(req,res){ //opening registos URL gets..
res.render("./registo/form_registo");
});

app.listen(8080,function(){
console.log("Servidor ativo no porto 8080"); });

Note: If there is an error about not finding the location of the ejs file, try to use the whole location instead of “./registo/form_registo”.

And just to appear something when opening the EJS file, put this simple HTML code on registo.ejs :

<!DOCTYPE html>                       
<html>
<head>
<h1> Registo do Utilizador</h1>
</head>
<body>
<form>
<table>
<tr>
<td>
Endereço de Email:
</td>
<td>
<input type=”text” email=””>
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type=”Password” name=””>
</td>
</tr>
</table>
</form>
</body>
</html>

The final result show on the browser should look like this:

Final Result in Firefox

--

--