Open In App

How to do Templating using ExpressJS in Node.js ?

Last Updated : 11 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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");
})
Filename: index.ejs html
<!--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:

Next Article

Similar Reads