How to make .js variables accessible to .ejs files ? - GeeksforGeeks

08 Apr, 2021
EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. It is possible to access JS variable in .ejs file.
You just need to pass the JS object as second parameter of res.render() method. Let’s jump into deep. 
Project Structure: Final folder structure will be as shown below.
Project
|
|-> node_modules
|-> views
  |-> index.ejs
|-> package.json
|-> package-lock.json
|-> server.js
Step 1: Initiate new Node JS project. Open a command prompt and create a new folder and initiate it with empty npm project.
mkdir Project
cd Project
npm init -y
Step 2: Install require dependencies.
Require dependencies:
Express JSEJS
Express JS
EJS
npm i express ejs
Step 3: Create a new server.js file in the Project directory. This file contains an API endpoint that is responsible to render an EJS file that generates HTML markup dynamically. Here render method takes two parameters. The first parameter is the EJS file and the second is a JS Object which automatically destructor in the .ejs file.
Here we pass .{firstName: “Geeks,”, lastName: “A Computer Science Portal”}as JS object.
server.js
const express = require('express');const path = require('path');    const ejs = require('ejs');   const app = express();const PORT = 3000;   // Set EJS as templating engineapp.set('view engine', 'ejs');   app.get('/', (req,res)=>{    // render method takes two parameters    // first parameter should be the .ejs file    // second parameter should be an object    // which is accessible in the .ejs file      // this .ejs file should be in views folder     // in the root directory.    res.render('index.ejs', {firstName: "Geeks,",                              lastName: "A Computer Science Portal"});})   // Start the serverapp.listen(PORT, err =>{    err ?     console.log("Error in server setup") :    console.log("Server listening on Port", PORT)});
Step 4: The default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make a file named “index.ejs” which is to be served on some desired request in our node project. The content of this page is:
index.ejs
<!DOCTYPE html><html>  <body style="text-align: center">    <h1 style="color: green"> GeeksforGeeks </h1>    <h3>         Welcome         <%= firstName %>         <%= lastName %>     </h3></body></html>
Here the passed object will be destructors. So, we can access the object property directly not need to use dot operator.
Step 5: Open command prompt on the root directory of your project and start the server using
node server.js
Output: If everything is going well you will see “Server listening on Port 3000”. Then open http://localhost:3000/  on your browser and you will see the following output on your screen.
Output:
Using array of .js in the .ejs file: We can also use the array in the ejs file as a variable, in this example that passes a JS array to the ejs file to render.
server.js
const author = {    name : 'Geeksforgeeks',    skills: ['DSA', 'Interview Experience', 'Web Developement', 'Puzzels',]}  app.get('/', (req,res)=>{    // render method takes two parameters    // first parameter should be the .ejs file    // second parameter should be an object    // which is accessible in the .ejs file      // this .ejs file should be in views folder     // in the root directory.    res.render('index.ejs', {author: author} );})
index.ejs
<!DOCTYPE html><html>  <body>    <h1 style="color: green"> GeeksForGeeks </h1>    <h3>         <%= author.name %> has skill on     </h3>      <ul>        <% author.skills.forEach((skill)=>{%>              <li><%=skill%></li>         <%});%>    </ul>  </body></html>
Output:
EJS-Templating Language
Express.js
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to build a basic CRUD app with Node.js and ReactJS ?
How to connect Node.js with React.js ?
Mongoose Populate() Method
Express.js req.params Property
How to Convert CSV to JSON file having Comma Separated values in Node.js ?
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript