* * *

This article is the third and last in the series of 3 articles on Node.js. You can view the first one here:- http://aasf.in/aasf/postdetails.php?link=66 and the second one here:- http://aasf.in/aasf/postdetails.php?link=67

In the previous article, we looked into how we can serve requests which have been received by our server, and how to send a response accordingly. 
In this article, we will look into how we can make use of those responses and integrate authorization and also contacts functionality with a client side application.

Before we get started, you need to know what a templating engine is. So what is a template? Think of a participation certificate in some competition. The certificate is the similar for every participant, except for their names. So you can think of a template as a certificate, and when you supply a name to the template or the certificate, the name will be printed on the certificate keeping rest of the details same for all the certificates.

EJS or Embedded JavaScript is a "Templating Engine". A templating engine is something to which we supply empty certificates(or templates) and dynamically supply data to it which will fill the empty spaces in the certificates(templates). So basically a templating engine is like a first year student who is given a huge set of certificates, and when a senior gives him/her a list of names, he/she has to fill those certificates with those names. This is exactly what EJS does as well. We supply it with different web pages, for example, a dashboard which has a welcome greeting saying "Welcome <YOUR NAME HERE>" and the <YOUR NAME HERE> part is dynamically rendered by the templating engine. So the "Welcome" part is a ready made certificate, and the <YOUR NAME HERE> part is the empty space which we will ask our templating engine to fill for us.

Let us understand this with a simple example.

Create a new directory by executing "mkdir EJSTutorial" in the terminal and change the directory using "cd EJSTutorial".

Run "npm init" to initialise your project. Let all the details be set to the default ones except for entry point, set the entry point to be app.js. Open this directory in your text editor.

Install basic dependencies which we will be needing by running the following command:-

npm install express express-session body-parser

This is also how you can install multiple libraries at the same time, by separating them with spaces.

In the EJSTutorial folder, create a folder named "public" and inside the public folder, create a file named "index.html". THE NAMING OF THESE FOLDERS AND FILE HAS TO BE EXACTLY THE SAME.

Paste the following code in the index.html file just created:-

<html>

<body>

<h1>Hello User!</h1>

</body>

</html>

Create a new file named "app.js" in the EJSTutorial directory and paste the following code in it:-

const express = require("express");

const session = require("express-session");

const bodyParser = require("body-parser");

 

const app = express();

 

app.use(express.static("public"));

 

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: false }));

 

app.use(

session({

secret: "seCReT",

resave: false,

saveUninitialized: true,

cookie: { maxAge: 360000 }

})

);

 

app.get("*", (req, res) => {

res.render("/index");

});

 

const PORT = 5000;

app.listen(PORT, console.log(`Server started on port ${PORT}`));

 Now start your server by running "node app.js" in your terminal. Go to "localhost:5000" in your browser and you should see "Hello User!" being displayed. So what just happened? 

app.use(express.static("public")); asks express to use the public folder to render any static files. 

res.render("/index"); :- res.render is used to render any kinds of files. When express sees "/index" in res.render, it checks in the public folder for a file named "index.html" and renders this file. But seeing "Hello User!" all the time is no fun, right? How can we render our name instead of "USER"? This is where we use templating engines.

We will need 2 modules to work with ejs, install them by running:-

npm install ejs express-ejs-layouts

First delete the index.html file in the public folder(THIS IS IMPORTANT, IF YOU DON'T DO THIS FILE WILL BE RENDERED ALWAYS IRRESPECTIVE OF WHAT YOU WRITE IN res.render).

Paste the following code in app.js in EJSTutorial directory:-

const express = require("express");

const expressLayouts = require("express-ejs-layouts");

const session = require("express-session");

const bodyParser = require("body-parser");

 

const app = express();

 

app.use(expressLayouts);

app.set("view engine", "ejs");

 

app.use(express.static("public"));

 

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: false }));

 

app.use(

session({

secret: "seCReT",

resave: false,

saveUninitialized: true,

cookie: { maxAge: 360000 }

})

);

 

app.get("*", (req, res) => {

res.render("sayHello", { user: "ENTER YOUR NAME HERE" });

});

 

const PORT = process.env.PORT || 5000;

 

app.listen(PORT, console.log(`Server started on port ${PORT}`));

In the EJSTutorial folder, create a folder named "views" and in this folder, create a file named "layout.ejs". (THE NAME IS IMPORTANT. DO NOT NAME IT ANYTHING ELSE). Paste the following code in that file:-

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<meta http-equiv="X-UA-Compatible" content="ie=edge" />

<title>Document</title>

</head>

<body>

<%-body%>

</body>

</html>

Create another file called "sayHello.ejs" in the views directory and paste the following code in it:-

<h1>Hello <%=user%></h1>

 Now restart your server and open "localhost:5000" and you should see "Hello ENTER YOUR NAME HERE", or if you did actually enter your name there, you will be seeing your name there. Let's see what happened here.

app.use(expressLayouts);
app.set("view engine", "ejs");

The above two lines tell express to use ejs as the templating engine for our project.

So how does the templating engine work? Whenever you want to render something, express first goes to the layout.ejs file in the views directory. This file is your certificate where you can fill anything you want in the empty spaces. In the layout.ejs file, you will see a line which says "<%-body%>". If the layout.ejs file is the certificate, then this line is where you will be rendering the name of the participant. Therefore, when we say res.render("sayHello"), the contents of the "sayHello.ejs" file get replaced in the "layout.ejs" file where "<%-body%>" is written. 

Additionally, you can go one layer deeper into this templating, and render dynamic content within the page you want to render as well. The second parameter that the res.render function receives is an object, which is a set of key, value pairs. So when I supplied the "sayHello.ejs" file with the object { user: "ENTER YOUR NAME HERE" }, this object and the user attribute became implicitly available in the "sayHello.ejs" file. You can print these variables in your html tags by using <%= VARIABLE %> syntax. 

Also notice that your html pages now have the extension of .ejs. This is to facilitate the usage of templates, variables and other such operations which will soon see.

You can also add control logic to your html page. You can run a for loop in your html page using the <% LOOP STATEMENT HERE %> syntax. Paste the following code in the sayHello.ejs file:-

<h1>

Hello

<%for(let i=0; i<2; ++i) {%>

<%=user%>

<%}%>

</h1>

and you should see your name bein printed twice now because of the for loop. (COMMON MISTAKE(I just committed this mistake and spent 15 mins wondering what the mistake was) : Do not use int or char for variables, remember, this is javascript, you can only use let, var and const) 

 

Let us implement a small application which will print a list of groceries:-

In the app.js file, replace the res.render function with the following code:-

res.render("sayHello", {

items: [

{

name: "Apple",

cost: "50"

},

{

name: "Maggi",

cost: "12"

}

]

});

and in the sayHello.ejs file, replace the code with the following code:-

<ul>

<%for(let i=0; i<2; ++i) {%>

<li>NAME : <%=items[i].name%> COST : <%=items[i].cost%></li>

<%}%>

</ul>

Restart your server and run it in the browser and you should see an unordered list of 2 elements.

Similarly, you can render whatever you wish to dynamically using EJS.

In case you want the user to be redirected to a certain page, you will use the res.redirect("<ENDPOINT NAME>") function. This function will send a GET request to the endpoint mentioned in its parameter. This will be useful when the user is already logged in, but is trying to access the login form again, in this case you will have to redirect him to his dashboard.

You can render the register page when someone sends a GET request to the "/users/register" endpoint, and render the personalised contacts page when someone sends a GET request to the "/users/contacts" endpoint dynamically. How? After fetching the rows from the database, send these rows in the object to the contacts page using res.render("contacts") and dynamically add the details of the contacts in that page using a for loop.

You can find the whole code for the contacts application here : https://github.com/GunaShekar02/Web-Week-2020/tree/master/backend

 

Summarizing, we first learned what templating engines are, and then used them to personalize data and render data dynamically in HTML pages.

 

This brings us to the end of the final article in the Node.js series. We first started off by learning what Node.js is and how to set up a simple Node.js server in the first article, learned how to service requests in the second article, and then learned how to render data dynamically using templating engines in this article.

 

This series of articles could not have been possible without the invaluable efforts of the co-organizers of Web Week 2020, Mallikarjun Katakam(https://www.linkedin.com/in/katakam-mallikarjun-668096183/) and Shweta Chaurasia(https://www.linkedin.com/in/shweta-chaurasia-419376187/).

 

In case of any queries, you can find me at https://www.linkedin.com/in/guna-shekar-proddaturi/.