Ejs Template Engine
Tags: ejs, javascript, express, coding
Published: 2022-11-02 18:45:28

## 
## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y8ykha6zslzkrydvagk6.png)

## 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](https://ejs.co/)
> [Handlebars](https://handlebarsjs.com/) 
> [Pug](https://pugjs.org/api/getting-started.html)


## 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

``` javascript
mkdir ejsdemo
```
``` javascript
cd ejsdemo
```

Initialize npm package.json file

``` javascript
npm init -y
```
Package.json File Code

``` javascript
{
  "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

``` javascript
npm i express
```

``` javascript
npm i ejs
```


Now After that Create one app.js file in root Directory and write this Code.

``` javascript
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.

``` javascript
node app.js
```

Code's Output Photo:

![Output Photo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1jex30jr4h8rsbaelhfo.png)

Now For Confirming Our Ejs Template Engine we need to write this line in app.js file.

``` javascript
// 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

``` html
<!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:

``` javascript
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:
![output Photo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jax0w19034c5h3q1jge3.png)

---


## 1. Passing data to render:- 

Update **app.js** like so:

``` javascript
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:

``` html
<!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:

![Output Photo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9tzvz948cchl5kughg4h.png)

---

## 2. If Else Conditional Syntax in Ejs:
Updated this code in App.js file

``` javascript
app.get("/", (req, res) => {
    let login = true;
    res.render("index", {
        login: login
    })
});
```
Updated code in index.ejs file

``` javascript
 <!-- if else Statement  -->
  <% if (login) { %>
  <h2> Welocome User </h2>
  <% } else { %>
  <h2> Please Login </h2>
  <% } %>
```


Output you should get this

![Output Photo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jl9uxmcaih5l592qa1v.png)

---

## 3. Loops in Ejs
App.js file code

``` javascript
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

``` javascript
<!-- for in loop  -->
    <% for (const key in stu) { %>
        <%= key %> - <%= stu[key] %>
        <br>
        <% } %>
```

Output Image 

![Output Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fevzsx18d87ve7u4xyca.png)

---

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xb9chq6e0hjzf49znccb.png)

header.ejs file code

``` javascript
<!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

``` javascript
</body>

</html>
```

index.ejs file Code

``` javascript
<%- 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 

![Output Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fevzsx18d87ve7u4xyca.png)

---

## 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](https://github.com/AKSHDESAI1/ejsdemo)