By Passing Data Object

Passing parameters via data object involves creating an object containing the parameters and passing it to the included template’s render function. In the main EJS template, you use <%- include(‘included_template.ejs’, data) %> to include the template and pass the data object. Then, in the included template, you can access the parameters using EJS syntax, such as <%= param1 %>.

HTML




<!-- main.ejs -->
 
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Main Template</title>
</head>
 
<body>
    <h1>Main Template</h1>
    <%- include('included_template.ejs', data) %>
</body>
 
</html>


Javascript




//server.js
 
const express = require('express');
const ejs = require('ejs');
const app = express();
 
app.set('view engine', 'ejs');
 
app.get('/', (req, res) => {
    const data = { param1: 'hello', param2: 'geek' };
    res.render('main', { data: data });
});
 
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});


Output:

How to include a template with parameters in EJS ?

EJS (Embedded JavaScript) is a templating language that enables dynamic content generation in HTML files using JavaScript syntax. EJS templates consist of HTML code mixed with JavaScript expressions enclosed within <% %> tags.

We will discuss the following approaches to include template with parameters in EJS

Table of Content

  • Using Custom Functions
  • Using Global Variables
  • By Passing Data Object
  • By Passing Parameters Directly

Similar Reads

Including Templates in EJS:

EJS provides an include function to include other EJS templates within a main template....

Steps to Create Application:

Step 1: Create a project folder using the following command....

Folder Structure:

...

Approach 1: Using Custom Functions

...

Approach 2: Using Global Variables

We define a custom function getParams in server.js to return an object with parameters. We pass this function as a parameter named getParams to the main.ejs template.In main.ejs, we call getParams() within the include statement to dynamically retrieve the parameters and pass them to the included template....

Approach 3: By Passing Data Object

...

Approach 4: By Passing Parameters Directly

...