Template Engine:-
A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.
There are many template engines available for Node.js. Each template engine uses a different language to define HTML template and inject data into it.
Advantages of Template engine in Node.js
Improves developer's productivity.
Improves readability and maintainability.
Faster performance.
Single template for multiple pages.
The following is a list of important (but not limited) template engines for Node.js
What is EJS?
EJS is one of the template engines used with Node JS to generate HTML markups with plain Javascript. EJS stands for Embedded JavaScript Templates. It can be used both on the client and the server-side.
EJS files are saved with the .ejs file extension.
Creating a Node Application and Installing Dependencies
Open terminal and run commands
mkdir ejsdemo
cd ejsdemo
Initialize npm package.json file
npm init -y
Package.json File Code
{
"name": "ejsdemo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "ejs",
"license": "ISC"
}
Install Dependency
npm i express
npm i ejs
Now After that Create one app.js file in root Directory and write this Code.
const express = require('express');
const ejs = require('ejs');
const app = express();
const PORT = 8000;
app.get("/", (req, res) => {
res.send("<h1> Hello World </h1>");
});
app.listen(PORT, () => {
console.log(`Server is Listening at ${PORT} Port.`);
})
Now for run the Server; write this command in termianl.
node app.js
Code's Output Photo:
Now For Confirming Our Ejs Template Engine we need to write this line in app.js file.
// Set Template Engine
app.set('view engine', 'ejs')
app.set('view engine', 'ejs') is self-explanatory. We are setting EJS as the Express app view engine.
Now we create one another folder named views and inside which we created one index.ejs file.
By default, Express will look inside of a views folder when resolving the template files, which is why we had to create a views folder.
Now; index.ejs code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1> Ejs is a Template Engine </h1>
</body>
</html>
Updated App.js file:
const express = require('express');
const ejs = require('ejs');
const app = express();
const PORT = 8000;
// Set Template Engine
app.set('view engine', 'ejs')
app.get("/", (req, res) => {
res.render("index");
});
app.listen(PORT, () => {
console.log(`Server is Listening at ${PORT} Port.`);
})
After running the server again; Output should be look like:
1. Passing data to render:-
Update app.js like so:
const express = require('express');
const ejs = require('ejs');
const app = express();
const PORT = 8000;
// Set Template Engine
app.set('view engine', 'ejs')
app.get("/", (req, res) => {
res.render("index", {
'firstName': 'Rohan',
'lastName': 'Patel'
});
});
app.listen(PORT, () => {
console.log(`Server is Listening at ${PORT} Port.`);
})
Update index.ejs like so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1> Ejs is a Template Engine </h1>
<h1 style="color: purple;"> Hi <%= firstName %> - <%= lastName %> </h1>
</body>
</html>
Run node app.js and you should get this:
2. If Else Conditional Syntax in Ejs:
Updated this code in App.js file
app.get("/", (req, res) => {
let login = true;
res.render("index", {
login: login
})
});
Updated code in index.ejs file
<!-- if else Statement -->
<% if (login) { %>
<h2> Welocome User </h2>
<% } else { %>
<h2> Please Login </h2>
<% } %>
Output you should get this
3. Loops in Ejs
App.js file code
app.get("/", (req, res) => {
let student = {
"20CE001" : "BHARGAV",
"20CE015" : "AYUSH",
"20CE016" : "KRUTIK",
"20CE018" : "BHARGAVI",
"20CE020" : "AKSH",
};
res.render("index", {
stu: student
})
});
index.ejs file code
<!-- for in loop -->
<% for (const key in stu) { %>
<%= key %> - <%= stu[key] %>
<br>
<% } %>
Output Image
4. EJS partials
Some parts of websites stay the same across different pages, like the header, footer, and sidebar. EJS provides us with partials that allow us to reuse views.
Now we Create another folder inside views named partials; inside which we create two files called header.ejs and footer.ejs.
Folder Structure Image:
header.ejs file code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
footer.ejs file code
</body>
</html>
index.ejs file Code
<%- include("partials/header") %>
<h1> Ejs is a Template Engine </h1>
<!-- for in loop -->
<% for (const key in stu) { %>
<%= key %> - <%= stu[key] %>
<br>
<% } %>
<%- include("partials/footer") %>
Output Image
Conclusion
In this article, we have reviewed template engines, and introduced EJS for JavaScript and how to use it. We have seen how to reuse code with partials and how we can also pass data to them.
Full Source Code Available Here: Github Link
Top comments (0)