Ejs Template Engine

akshdesai1

AKSH DESAI

Posted on November 2, 2022

Ejs Template Engine

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.

Template Engine Photo

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

Ejs
Handlebars
Pug

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
Enter fullscreen mode Exit fullscreen mode
cd ejsdemo
Enter fullscreen mode Exit fullscreen mode

Initialize npm package.json file

npm init -y
Enter fullscreen mode Exit fullscreen mode

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"
}

Enter fullscreen mode Exit fullscreen mode

Install Dependency

npm i express
Enter fullscreen mode Exit fullscreen mode
npm i ejs
Enter fullscreen mode Exit fullscreen mode

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.`);
})
Enter fullscreen mode Exit fullscreen mode

Now for run the Server; write this command in termianl.

node app.js
Enter fullscreen mode Exit fullscreen mode

Code's Output Photo:

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')
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.`);
})
Enter fullscreen mode Exit fullscreen mode

After running the server again; Output should be look like:
output Photo


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.`);
})
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Run node app.js and you should get this:

Output Photo


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
    })
});
Enter fullscreen mode Exit fullscreen mode

Updated code in index.ejs file

 <!-- if else Statement  -->
  <% if (login) { %>
  <h2> Welocome User </h2>
  <% } else { %>
  <h2> Please Login </h2>
  <% } %>
Enter fullscreen mode Exit fullscreen mode

Output you should get this

Output Photo


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
    })
});
Enter fullscreen mode Exit fullscreen mode

index.ejs file code

<!-- for in loop  -->
    <% for (const key in stu) { %>
        <%= key %> - <%= stu[key] %>
        <br>
        <% } %>
Enter fullscreen mode Exit fullscreen mode

Output Image

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:

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>
Enter fullscreen mode Exit fullscreen mode

footer.ejs file code

</body>

</html>
Enter fullscreen mode Exit fullscreen mode

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") %>
Enter fullscreen mode Exit fullscreen mode

Output Image

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

💖 💪 🙅 🚩
akshdesai1
AKSH DESAI

Posted on November 2, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Ejs Template Engine
ejs Ejs Template Engine

November 2, 2022