EJS or Embedded Javascript Templating is a templating engine used by Node.js. Template engine helps to create an HTML template with minimal code. Also, it can inject data into an HTML template on the client side and produce the final HTML. EJS is a simple templating language that is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript into HTML pages.
Install require dependencies.
npm i express ejs
const express = require('express');
const ejs = require('ejs');
const app = express();
const PORT = 3000;
// Set EJS as templating engine
app.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.
let data = {
subject: ['Maths', 'English', 'Computer Science']
}
res.render('home', { data: data });
})
// Start the server
app.listen(PORT, err =>{
err ?
console.log("Error in server setup") :
console.log("Server listening on Port", PORT)
});
<!DOCTYPE html>
<html>
<body>
Hello
<ul>
<% data.subject.forEach((item)=>{%>
<li>
<%=item%>
</li>
<%});%>
</ul>
</body>
</html>
Output
Hello
. Maths
. English
. Computer Science