Open In App

How to pass Variable to inline JavaScript using EJS Template Engine?

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In the EJS templating engine, we can pass variables to inline JS within our HTML templates. We can use the ‘<%= variable %>‘ syntax, where we can embed server-side variables directly into the client-side scripts. In this article, we will explore the detailed process to pass a variable to inline javascript using the EJS templating engine in terms of practical examples with output.

What is EJS templating Engine?

EJS (Embedded JavaScript) is a popular templating engine for Node.js that allows to generate HTML markup with JavaScript. One common requirement in web development is passing variables from server-side code to client-side JavaScript for dynamic content rendering and interaction.

Syntax for passing variable:

<script>
var myVariable = '<%= serverSideVariable %>';
// use myVariable in JS code
</script>

Steps to pass a variable to inline javascript using EJS templating engine

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

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

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

Step 4: Now create the below Project Structure in your project which includes app.js and views/index.ejs files.

PS

Step 5: Now, create the required files and add the following codes.

HTML




<!-- views/index.ejs -->
 
<!DOCTYPE html>
 
<head>
    <title>Example</title>
</head>
 
<body>
    <h1>Welcome to GeeksforGeeks!</h1>
    <script>
        // inline JavaScript
        var message = '<%= data.message %>';
        alert(message);
    </script>
</body>
 
</html>


Javascript




//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) => {
    const data = {
        message: 'Hello from GeeksforGeeks!'
    };
    res.render('index', { data });
});
app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});


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

node app.js

Output:

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads