Template Engine : A template engine basically helps us to use the static template files with minimal code. At runtime, the template engine replaces all the variables with actual values at the client-side.
Templating Engine Examples:
- EJS (Embedded JavaScript Templating)
- Pug
- Mustache
In this article we are going to use EJS engine.
Setting up NPM packages:
npm init -y
- Installing Dependencies
npm install ejs express --save
Basic ExpressJS Server:
Javascript
const express = require('express');const app = express(); app.get('/' , (req , res)=>{ res.send("GeeksforGeeks");}) app.listen(4000 , ()=>{ console.log("server is running on port 4000");}) |
Output:
Adding of EJS Engine: Here we need to set ejs as our view engine.
Javascript
const express = require('express');const app = express(); app.set('view engine', 'ejs'); app.get('/' , (req , res)=>{ res.send("GeeksforGeeks");}) app.listen(4000 , ()=>{ console.log("server is running on port 4000");}) |
index.ejs
<!--Ejs File--><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body> <h1>GeeksforGeeks</h1></body></html> |
Output:
output
Rendering of EJS file:
Javascript
const express = require('express');const app = express(); app.set('view engine', 'ejs'); app.get('/:name' , (req , res)=>{ res.render("index" , { data : req.params.name });}) app.listen(4000 , ()=>{ console.log("server is running on port 4000");}) |
Storing of data : Here we have to store the data var name = "<%= data %>".
Javascript
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript"> var name = "<%= data %>" setTimeout(()=>{ document.getElementById('hello').innerHTML = name; },1000); </script></head><body> <h1 id="hello"></h1></body></html> |
Output:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.


