Open In App

How to Access EJS Variable in Javascript Logic ?

EJS stands for Embedded JavaScript. It is a templating language used to generate dynamic HTML pages with data from the server by embedding JavaScript code.

Features of EJS

Steps to Access EJS variable in Javascript logic

Step 1: Firstly, we will make the folder named root by using the below command in the VScode Terminal. After creation use the cd command to navigate to the newly created folder.

mkdir root
cd root

Step 2: Once the folder is been created, we will initialize NPM using the below command, this will give us the package.json file.

npm init -y

Step 3: Once the project is been initialized, we need to install Express and EJS dependencies in our project by using the below installation command of NPM.

npm i express ejs

Project Structure

PS


The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2",
"ejs": "^3.1.9",
}

Explanation:

Example: Below is an example of Accessing EJS variable in Javascript logic.

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

<head>
    <title>Access EJS Variable in JS</title>
</head>

<body>
    <h1>Hello,
        <%if(role=='Admin'){%>
            <%= name %>
                <%}else{%>
                    Guest
                    <%}%>
                        !
    </h1>

    <script>
        var role = '<%= role %>';

        if (role === 'Admin') {
            alert('Welcome to GFG, Admin!');
        } else {
            alert('Welcome to GFG, Guest!');
        }
    </script>
</body>

</html>
// app.js

const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 4000;

// Set the view engine to EJS
app.set('view engine', 'ejs');

// Define a route to render the HTML file
app.get('/', (req, res) => {
  res.render('index', { role: 'Admin', name: 'GFG' });
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Output:

lv_0_20240317002559

Article Tags :