Wednesday, November 2, 2022
HomeWordPress DevelopmentEjs Template Engine - DEV Neighborhood 👩‍💻👨‍💻

Ejs Template Engine – DEV Neighborhood 👩‍💻👨‍💻




Template Engine:-

A template engine allows you to use static template recordsdata in your utility. At runtime, the template engine replaces variables in a template file with precise values, and transforms the template into an HTML file despatched to the shopper. This strategy makes it simpler to design an HTML web page.

There are lots of template engines out there for Node.js. Every template engine makes use of a unique language to outline HTML template and inject knowledge into it.

Template Engine Photo



Benefits of Template engine in Node.js

Improves developer’s productiveness.
Improves readability and maintainability.
Sooner efficiency.
Single template for a number of pages.

The next is an inventory of necessary (however not restricted) template engines for Node.js

Ejs
Handlebars
Pug



What’s EJS?

EJS is without doubt one of the template engines used with Node JS to generate HTML markups with plain Javascript. EJS stands for Embedded JavaScript Templates. It may be used each on the shopper and the server-side.

EJS recordsdata are saved with the .ejs file extension.



Making a Node Utility and Putting in Dependencies

Open terminal and run instructions

mkdir ejsdemo
Enter fullscreen mode

Exit fullscreen mode

cd ejsdemo
Enter fullscreen mode

Exit fullscreen mode

Initialize npm package deal.json file

npm init -y
Enter fullscreen mode

Exit fullscreen mode

Package deal.json File Code

{
  "identify": "ejsdemo",
  "model": "1.0.0",
  "description": "",
  "fundamental": "index.js",
  "scripts": {
    "check": "echo "Error: no check specified" && exit 1"
  },
  "key phrases": [],
  "writer": "ejs",
  "license": "ISC"
}

Enter fullscreen mode

Exit fullscreen mode

Set up Dependency

npm i categorical
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 Listing and write this Code.

const categorical = require('categorical');
const ejs = require('ejs');

const app = categorical();
const PORT = 8000;


app.get("/", (req, res) => {
    res.ship("<h1> Hi there World </h1>");
});

app.hear(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 Picture:

Output Photo

Now For Confirming Our Ejs Template Engine we have 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’re setting EJS because the Categorical app view engine.

Now we create each other folder named views and inside which we created one index.ejs file.

By default, Categorical will look within a views folder when resolving the template recordsdata, which is why we needed to create a views folder.

Now; index.ejs code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Appropriate" content material="IE=edge">
    <meta identify="viewport" content material="width=device-width, initial-scale=1.0">
    <title>Doc</title>
</head>
<physique>
        <h1> Ejs is a Template Engine </h1>
</physique>
</html>
Enter fullscreen mode

Exit fullscreen mode

Up to date App.js file:

const categorical = require('categorical');
const ejs = require('ejs');

const app = categorical();
const PORT = 8000;

// Set Template Engine 
app.set('view engine', 'ejs')

app.get("/", (req, res) => {
    res.render("index");
});

app.hear(PORT, () => {
    console.log(`Server is Listening at ${PORT} Port.`);
})
Enter fullscreen mode

Exit fullscreen mode

After working the server once more; Output needs to be appear like:
output Photo




1. Passing knowledge to render:-

Replace app.js like so:

const categorical = require('categorical');
const ejs = require('ejs');

const app = categorical();
const PORT = 8000;

// Set Template Engine 
app.set('view engine', 'ejs')

app.get("/", (req, res) => {
    res.render("index", {
        'firstName': 'Rohan',
        'lastName': 'Patel'
    });
});

app.hear(PORT, () => {
    console.log(`Server is Listening at ${PORT} Port.`);
})
Enter fullscreen mode

Exit fullscreen mode

Replace index.ejs like so:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Appropriate" content material="IE=edge">
    <meta identify="viewport" content material="width=device-width, initial-scale=1.0">
    <title>Doc</title>
</head>
<physique>
    <h1> Ejs is a Template Engine </h1>
    <h1 model="coloration: purple;"> Hello <%= firstName %> - <%= lastName %> </h1>
</physique>
</html>
Enter fullscreen mode

Exit fullscreen mode

Run node app.js and it is best to get this:

Output Photo




2. If Else Conditional Syntax in Ejs:

Up to date this code in App.js file

app.get("/", (req, res) => {
    let login = true;
    res.render("index", {
        login: login
    })
});
Enter fullscreen mode

Exit fullscreen mode

Up to date code in index.ejs file

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

Exit fullscreen mode

Output it is best to get this

Output Photo




3. Loops in Ejs

App.js file code

app.get("/", (req, res) => {
    let pupil = {
        "20CE001" : "BHARGAV",
        "20CE015" : "AYUSH",
        "20CE016" : "KRUTIK",
        "20CE018" : "BHARGAVI",
        "20CE020" : "AKSH",
    };
    res.render("index", {
        stu: pupil
    })
});
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 Picture

Output Image




4. EJS partials

Some components of internet sites keep the identical throughout completely different pages, just like the header, footer, and sidebar. EJS offers us with partials that permit us to reuse views.

Now we Create one other folder inside views named partials; inside which we create two recordsdata known as header.ejs and footer.ejs.

Folder Construction Picture:

Folder Structure Image

header.ejs file code

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Appropriate" content material="IE=edge">
  <meta identify="viewport" content material="width=device-width, initial-scale=1.0">
  <title>Doc</title>
</head>

<physique>
Enter fullscreen mode

Exit fullscreen mode

footer.ejs file code

</physique>

</html>
Enter fullscreen mode

Exit fullscreen mode

index.ejs file Code

<%- embrace("partials/header") %>
<h1> Ejs is a Template Engine </h1>

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

<%- embrace("partials/footer") %>
Enter fullscreen mode

Exit fullscreen mode

Output Picture

Output Image




Conclusion

On this article, we’ve reviewed template engines, and launched EJS for JavaScript and the way to use it. Now we have seen the way to reuse code with partials and the way we are able to additionally cross knowledge to them.

Full Supply Code Obtainable Right here: Github Hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments