Node JS Tutorial - Partial Templates

In this tutorial, we will learn about Partial Templates in EJS, which help us avoid repetition of the same code on several web pages.

Creating Partial Templates

Let's create a folder inside the views directory. Click on "New Folder" and name it "partials". Inside the partials folder, create three new files: "head.ejs", "header.ejs", and "footer.ejs".

Open the "head.ejs" file and add the Bootstrap CDN. Go to getbootstrap.com and copy the Bootstrap CSS CDN. Paste it inside the "head.ejs" file.

Next, copy the Bootstrap JavaScript CDN and paste it inside the "footer.ejs" file.

Creating Navigation and Footer

Open the "header.ejs" file and create a navigation menu:


<nav class="nav">
<a class="nav-link" href="/">Home</a>
<a class="nav-link" href="/about">About</a>
<a class="nav-link" href="/contact">Contact</a>
</nav>

Open the "footer.ejs" file and add the following content:


<footer class="footer">
<p class="text-center">© 2020 Surfside Media. All rights reserved</p>
</footer>

Using Partial Templates

Now, let's use these partial templates in our home, about, and contact pages. Open the "home.ejs" file and add the following code inside the head section:


<%- include('partials/head') %>

Inside the body section, add the header:


<%- include('partials/header') %>

At the bottom of the page, add the footer:


<%- include('partials/footer') %>

Running the Application

Run the application by going to the command prompt and running the command:


node index.js

Switch to the browser and refresh the page. You should see the partial templates header and footer. Click on the about page, and you should see the about page. Click on the contact page, and you should see the contact us page.

This is how you can use partial templates in Node.js.