How to use Partials In EJS
EJS supports partials, which are reusable snippets of code. To use partials, you typically create a partials directory inside views.
Create a Header Partial:
In views/partials/header.ejs, add some HTML content.
<header>
<h1>Welcome to GFG EJS data passsing example</h1>
</header>
Create a Footer Partial:
In views/partials/footer.ejs, add some HTML content.
<footer>
<p>Copyright © from footer</p>
</footer>
Include the Partial:
Modify index.ejs to include the partials.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Exapmle</title>
</head>
<body>
<%- include("partials/header.ejs") %>
<h1>
Hello <%= name %>!
</h1>
<ul>
<% items.forEach(item => { %>
<li><%= item %></li>
<% }) %>
</ul>
<%- include("partials/footer.ejs") %>
</body>
</html>
The <%- include(“partials/header”) %> and <%- include(“partials/footer.ejs”) %> line includes the content of header.ejs and footer.ejs in the index.ejs template.
Output:
Passing Data to EJS Templates
EJS (Embedded JavaScript) is a simple templating language that lets you induce HTML language with plain JavaScript. It’s especially popular in Node.js operations for rendering dynamic web runners. It is used to dynamically render HTML pages on the server side. This article will give a detailed companion on how to pass data to EJS templates.