Open In App

How to include a template with parameters in EJS?

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In EJS, we can include templates with parameters for the reuse of modular components in web applications. By passing parameters during the inclusion, we can create interactive templates. In this article, we will see a practical example of including a template with parameters in EJS. Below is the syntax to include a template with parameters in EJS.

Syntax to include template with parameters:

<%- include('template.ejs', {param1: value1, param2: value2, ...}) %> 

Steps to include a template with parameters in EJS:

Step 1: Firstly, we will make the folder named root by using the below command in the VScode Terminal. After creation use the cd command to navigate to the newly created folder.

mkdir root
cd root

Step 2: Once the folder is been created, we will initialize NPM using the below command, this will give us the package.json file.

npm init -y

Step 3: Once the project is been initialized, we need to install Express and EJS dependencies in our project by using the below installation command of NPM.

npm i express ejs

Step 4: Now create the below Project Structure in your project which includes app.js, views/index.ejs, and views/footer.ejs files.

Folder Structure:

PS

The updated dependencies in package.json will look like:

"dependencies": {
"express": "^4.18.2",
"ejs": "^3.1.9",
}

Approach to include template with parameters in EJS:

  • In the above example, we are passing the information to the EJS template using res.render('index', { data: temp}).
  • We have included a footer template with the dynamic parameters in the main template using <%- include('footer.ejs', { year: new Date().getFullYear() }) %>.

Example: Now, we need to write the code for the app.js file, code for views/index.ejs to include a template with parameters and code for views/footer.ejs which defines as a template and passes the year to the main template.

HTML
<!-- views/index.ejs -->
<!DOCTYPE html>
<html>
<head>
	<title>
		<%= data.title %>
	</title>
</head>

<body>
	<h1 style="color: green;">
		<%= data.title %>
	</h1>
	<p>
		<%= data.description %>
	</p>
	<h2>Popular Topics:</h2>
	<ul>
		<% data.topics.forEach(topic=> { %>
			<li>
				<%= topic %>
			</li>
			<% }); %>
	</ul>
	<%- include('footer.ejs', { year: new Date().getFullYear() }) %>
</body>

</html>
HTML
<!-- views/footer.ejs -->

<footer>
	© <%= year %> GeeksforGeeks
</footer>
JavaScript
const express = require('express');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
const temp = {
	title: 'GeeksforGeeks',
	description: 'A computer science portal for geeks.',
	topics: ['Algorithms', 'Data Structures', 'Web Development'],
};
app.get('/', (req, res) => {
	res.render('index', { data: temp });
});
app.listen(port, () => {
	console.log(
		`Server is running at
		http://localhost:${port}`
	);
});

To run the application, we need to start the server by using the below command.

node app.js

Output:

Output

Updated Syntax and code:

Syntax to include template with parameters:

We can include two template in two ways like:

<%- include('template.ejs', {param1: value1, param2: value2, ...}) %> 

And in the second way we do not need to define any file extension like ".ejs" or not.

<%- include('template', {param1: value1, param2: value2, ...}) %> 


Updated code:

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= data.title %></title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            margin: 0;
            padding: 0;
            line-height: 1.6;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            margin-top: 20px;
        }

        h1 {
            font-size: 2.5rem;
            color: #17ed0c;
            margin-bottom: 10px;
        }

        p {
            font-size: 1.1rem;
            margin-bottom: 20px;
        }

        h2 {
            font-size: 1.8rem;
            color: #007bff;
            margin-bottom: 10px;
        }

        ul {
            list-style: none;
            padding: 0;
        }

        li {
            font-size: 1.1rem;
            padding: 10px 0;
            border-bottom: 1px solid #e1e1e1;
        }

        footer {
            margin-top: 30px;
            padding: 15px;
            background-color: #333;
            color: #fff;
            text-align: center;
            border-radius: 0 0 8px 8px;
        }

        @media (max-width: 600px) {
            .container {
                padding: 10px;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <h1><%= data.title %></h1>
        <p><%= data.description %></p>
        <h2>Popular Topics:</h2>
        <ul>
            <% data.topics.forEach(topic => { %>
                <li><%= topic %></li>
            <% }); %>
        </ul>
        <%- include('footer', { year: new Date().getFullYear() }) %>
    </div>
</body>

</html>
HTML
<footer>
    <p>© <%= year %> GeeksforGeeks. All rights reserved.</p>
</footer>
JavaScript
const express = require('express');
const app = express();
const port = 3000;

app.set('view engine', 'ejs');

const temp = {
    title: 'GeeksforGeeks',
    description: 'A computer science portal for geeks.',
    topics: ['Algorithms', 'Data Structures', 'Web Development'],
};

app.get('/', (req, res) => {
    res.render('index', { data: temp });
});

app.listen(port, (err) => {
    if (err) {
        console.log(err);
    } else {
        console.log(`Server is running at port no ${port}`);
    }
});

Output:

compressed_Screenshot-(509)
Output

Next Article

Similar Reads