Steps to Implement EJS in Express
Step 1: Create a NodeJS application using the following command:
npm init
Step 2: Install required Dependencies:
npm i ejs express
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2"
}
Example: The below example is demonstrating the EJS View Engine for Express.
<!-- views/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>EJS Example</title>
<style>
h1 {
color: green;
}
</style>
</head>
<body>
<h1>w3wiki | EJS View Engine</h1>
<h2>Welcome, <%= name %>
</h1>
<p>Your email is: <%= email%>
</p>
</body>
</html>
// index.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
// Set EJS as the view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Define a route to render the Pug
// template when the root path is accessed
app.get('/', (req, res) => {
//Sending this data from Server
const data = {
name: "jaimin",
email: "jaimin@gmail.com"
};
// Render the EJS template named 'index' and pass the data
res.render('index', data);
});
// Start the server and listen on the specified port
app.listen(port, () => {
// Display a message when the server starts successfully
console.log(`Server is running at http://localhost:${port}`);
});
Step 4: To run the application use the following command
node index.js
Output: Now go to http://localhost:3000 in your browser:
Getting Started with View Engine
A view engine is a tool used in web development to create dynamic HTML content based on data from the server. It acts as a template processor, allowing developers to integrate data with predefined HTML templates easily. View engines are commonly used in frameworks like Express.js for Node.js, Django for Python, and Ruby on Rails. There are different view engines available for various programming languages, such as EJS, Pug, Handlebars, Django, Freemarker, and more.