Steps to use EJS Template Engine

Step 1: Create the below Project Structure to demonstrate the use of the EJS Template. The Project Structure includes app.js and views/index.ejs files.

Step 2: Use the below code for app.js to set up a basic Node.js server using Express and EJS. We will handle user input and pass it to the EJS template using this file. Also, use the below code for views/index.ejs file which includes a form for user input and dynamic message displaying.

HTML
<!DOCTYPE html>
<head>
    <title>EJS Template Example</title>
</head>
<body>
    <h1>Hello, <%= username %>!</h1>
    <form action="/greet" method="post">
        <label for="username">Enter your name:</label>
        <input type="text" id="username" 
               name="username" required>
        <button type="submit">Greet</button>
    </form>
</body>
</html>
Javascript
const express = require('express');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
    res.render('index.ejs', { username: 'Guest' });
});
app.post('/greet', (req, res) => {
    const { username } = req.body;
    res.render('index.ejs', { username }); 
});
app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});

Step 3: To run the application, we need to start the server by using the below command.

node app.js

Output:

Explanation of Output:

  • The above example demonstrates he use of an EJS template in a Node.js web application.
  • The app.js file has the Express Server, which defines the routes to render an EJS template (index.ejs) and handles the user input through the form.
  • The EJS Template mainly displays a simple greeting message based on the user’s input.

How to Install & Use EJS Template Engine ?

EJS (Embedded JavaScript) is mainly a templating language for JS which allows dynamic content generation in web-based applications. This EJS Template allows us to embed the JS code directly in the HTML markup, which enables the integration of data and logic into the presentation layer. We can use EJS Templates with Node.js and Express.js to create dynamic web applications for rendering data on the server side.

In this article, we will explore the process of installing the EJS Template and also we will see the interactive example of the EJS Template Engine.

Table of Content

  • Steps to Install EJS Template Engine
  • Steps to use EJS Template Engine

Similar Reads

Prerequisites

Node JSExpress JS...

Steps to Install EJS Template Engine

Step 1: In the first step, we will create the new folder as ejs-template by using the below command in the VSCode terminal....

Steps to use EJS Template Engine:

Step 1: Create the below Project Structure to demonstrate the use of the EJS Template. The Project Structure includes app.js and views/index.ejs files....