EJS Template Engine or EJS is a popular template engine for web development. it is used in Nodejs. It allows you to generate dynamic content by embedding JavaScript to HTML content. EJS serves as a templating language, utilizing plan javascript to HTML.
Features:
- Template Reusability: Reuse common components with partials.
- Data Escaping: Auto-escapes HTML to prevent XSS attacks.
- Custom Delimiters: Allows flexible template syntax.
Syntax:
<h1>Hello, <%= username %></h1>Why Choose EJS
EJS offers several advantages that make it a popular choice:
- Ease of Integration: EJS easily integrates with Node.js applications, making it convenient for users already using JavaScript on the server side.
- Familiar Syntax: Those who are comfortable with JavaScript will find EJS easy to grasp, as it allows them to use JavaScript directly within their HTML templates.
- Robustness: EJS provides powerful features like loops, conditionals, and partials, allowing for complex template structures to be easily implemented.
How Does EJS Template Engine Work
- Parses HTML files with embedded JavaScript.
- Executes the JavaScript code to generate dynamic content.
- Replaces embedded code with actual data.
- Sends the final HTML markup to the client’s browser for rendering.
Steps to implement EJS in Node Application:
we are creating a `hello,world!` page using EJS engine. To create a simple "hello, world" page using EJS,you'll need to follow these steps:
Step 1: Create the folder in which you want to make EJS template.
mkdir ejs-template
cd ejs-templateStep 2: Initialize the Node application using the following command.
npm init -yStep 3: Install the required dependencies:
npm install ejs expressFolder Structure:
The updated dependencies in package.json file will :
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.3"
}Example: Create the required folders and files and add the required codes.
<!-- views/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello, World!</title>
</head>
<body>
<h1>
<%= message %>
</h1>
</body>
</html>
//app.js
const express = require('express');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.get('/', (req, res) => {
res.render('index', { message: 'Hello, World!' });
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
To start the server run the following command:
node app.jsOutput:
