Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to write a function in JavaScript ?
Next article icon

How to use Ejs in JavaScript ?

Last Updated : 08 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

EJS or Embedded Javascript Templating is a templating engine used by Node.js. The template engine helps to create an HTML template with minimal code. Also, it can inject data into the HTML template on the client side and produce the final HTML.

Installation Steps

Install the module using the following command:

npm install ejs --save 

Note:

In the commands above, “npm” stands for the Node Package Manager, which is where all the dependencies are stored. The
“–save” flag is no longer needed after Node 5.0.0, as all the modules we install will now be added to dependencies automatically.

To start, we need to set EJS as our templating engine with Express. Express is a Node.js web application server framework designed for building single-page, multi-page, and hybrid web applications. It has become the standard server framework for Node.js.

Data passed from the server is sent to the EJS file and then we can access that data using the below line and it will give that data to h, p, or another text tag.

<%= data %>

If we want to use this data for normal js operations like if-else and loops or other programming statements we can write it in the following form:

<% if(data == "1"){%>
<h5>Cricket</h5>
<%}else{%>
<h5>Football</h5>
<%}%>

Now to access that data in the script tag of the EJS file or the .js file all you need to do is to pass that data in another variable as below:

let data = '<%-data%>'

Now you can perform any operation on the data variable that has the same value as the EJS passed data variable.

Example: Implementation to use EJS in our project.

javascript
// Filename - index.js  // Set express as Node.js web application  // server framework.   // Install it using 'npm install express' command  // and require like this: let express = require('express');  let app = express();     // Set EJS as templating engine  app.set('view engine', 'ejs');   app.get("/", function(req, res) {     res.render("home", {name:'Chris Martin'}); });    // Server setup app.listen(3000, function(req, res) {   console.log("Connected on port:3000"); }); 

The default behaviour 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 “home.ejs” which is to be served on some desired request in our node project.

HTML
<!-- home.ejs -->  <!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0"> </head>  <body>         <!-- Text from EJS variable              passed from server -->         <h2>             Text from EJS variable passed             from server is =         </h2>         <h2 style="color:red">             <%=name%>         </h2>         <br>          <!-- Text from EJS variable              passed from script tag -->         <h2 style="color: blue;">             Text from EJS variable passed             from script tag =         </h2>         <h2 style="color: blue;" id="text_from_script">         </h2>         <br>          <!-- Text from EJS variable passed              from script tag after manipulation -->         <h2 style="color: green;">             Text from EJS variable passed from             script tag after manipulation =         </h2>         <h2 style="color: green;"              id="text_from_script_manipulated">         </h2>      <script>         let name = '<%-name%>'         let heading = document             .getElementById('text_from_script');          heading.innerText = name;         name = "Mr. " + name;         let heading_man = document.getElementById(             'text_from_script_manipulated');         heading_man.innerText = name;      </script> </body>  </html> 

The “name” variable has been passed from the server to the ‘name.ejs’ file and displayed using an h2 tag. To use the “name” variable in the script tag, all we did was declare a variable and assign the EJS variable to the declared variable using:

let name = '<%-name%>'

Step to Run Application: Run the application using the following command from the root directory of the project

node index.js

Output:



Next Article
How to write a function in JavaScript ?

S

sethivansh6
Improve
Article Tags :
  • JavaScript
  • Node.js
  • Web Technologies
  • Node.js-Misc

Similar Reads

  • How to trigger events in JavaScript ?
    JavaScript is a high-level, interpreted, dynamically typed client-side scripting language. While HTML is static and defines the structure of a web page, JavaScript adds interactivity and functionality to HTML elements. This interaction is facilitated through events, which are actions or occurrences
    2 min read
  • How to use Polyfill in JavaScript ?
    A polyfill in JavaScript is a script that adds modern features to older browsers that do not natively support them. To use it, include the polyfill script in your HTML or install it via a package manager, ensuring compatibility with older environments. Polyfill and its featuresBroad Compatibility: P
    3 min read
  • How JavaScript Works?
    JavaScript is a dynamically typed, cross-platform threaded scripting and programming language, used to put functionality and interactivity at the client side as well as to write logic on the server side of a website. It can display content updates, interactive maps, control multimedia, interactive f
    14 min read
  • How to write a function in JavaScript ?
    JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
    4 min read
  • How are DOM utilized in JavaScript ?
    What is DOM The document object Model (DOM) represents the full HTML document. When an HTML document is loaded within the browser, it becomes a document object. The root element represents the HTML document, its properties, and its methods. With the assistance of a document object, we will add dynam
    3 min read
  • 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 EJSDynamic Content: Based on data from servers or other sources, we can generate a dynamic HTML template.Partial Templates: Partials
    3 min read
  • Uses of JavaScript
    JavaScript is a versatile programming language extensively used in web development. It empowers interactive features like form validation, dynamic content updates, and user interface enhancements. Furthermore, it's employed in server-side scripting, mobile app development, game development, and even
    3 min read
  • How to Run JavaScript in Visual Studio?
    To run JavaScript in Visual Studio, you can either use Node.js in the Terminal or the Code Runner extension. Both methods allow you to execute JavaScript code easily and efficiently within the Visual Studio environment. Using Node.js in TerminalNode.js is a JavaScript runtime that allows you to exec
    2 min read
  • How to use express in typescript ?
    In this article, we will see how to use Express in TypeScript. The TypeScript is a superset of JavaScript that provides type notation with the JavaScript, so we can handle our server, and very scalable for the future. Express is web framework helps to create server-side handling with the help of Nod
    2 min read
  • How to Add JavaScript in HTML Document?
    To add JavaScript in HTML document, several methods can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file. Inline JavaScriptYou can write JavaScript code directly inside the HTML element using the onclick, onmouseover, or other e
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences