Bootcamp
Search…
3.2.3: EJS Partials

Introduction

EJS "partials" are EJS templates we can inject into other EJS templates. This is useful for common EJS used across other EJS templates such as headers, footers, and navigation bars. Each partial has its own file like other EJS templates, and we can include a partial in an EJS template with the <%- %> EJS tag and include keyword.

EJS Includes

  1. 1.
    EJS Includes render partial EJS templates (i.e. may not represent standalone HTML page) into other EJS templates.
  2. 2.
    The following example includes an EJS partial at line 3. The 1st param to include is the path to the partial, and the 2nd param is the data to pass to the partial.
    1
    <ul>
    2
    <% users.forEach(function(user) { %>
    3
    <%- include('user/details', {user: user}); %>
    4
    <% }); %>
    5
    </ul>
    Copied!
  3. 3.
    Read more on EJS Includes here.

Headers and Footers as Partials

  1. 1.
    A common pattern is to remove all boilerplate code inside of EJS files to highlight distinct logic in each EJS template. Boilerplate refers to code that is repeated in multiple places.
  2. 2.
    For example, HTML header and footer code that is shared across all pages can be abstracted into partials. Headers may include navbars, and footers may include links and copyrights.

recipe.ejs

We abstracted header and footer HTML into header.ejs and footer.ejs respectively. We pass dynamic data to the header EJS partial on line 1. Note there is no need to use the <%= => EJS tag to inject variables that are already in a <%- %> tag.
1
<%- include('header', {title: `Recipe: ${recipe.title}`}); -%>
2
​
3
<h1>Recipe: <%= recipe.title %></h1>
4
<p>Instructions</p>
5
...
6
​
7
<%- include('footer'); -%>
Copied!

header.ejs

  1. 1.
    Notice this file only has an opening body tag. The closing body tag is in footer.ejs.
  2. 2.
    Notice we pass the page title (text that appears in browser tab) into include in recipe.ejs.
1
<html>
2
<head>
3
<!-- Required meta tags -->
4
<meta charset="utf-8" />
5
<meta
6
name="viewport"
7
content="width=device-width, initial-scale=1, shrink-to-fit=no"
8
/>
9
​
10
<!-- Bootstrap CSS -->
11
<link
12
rel="stylesheet"
13
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
14
integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
15
crossorigin="anonymous"
16
/>
17
​
18
<title><%= title %></title>
19
</head>
20
<body>
Copied!

footer.ejs

1
</body>
2
</html>
Copied!