Home »
Node.js
EJS partials
EJS partials: Here, we are going to learn about the EJS partials, which are used to help us to avoid repetition of the same code on several web pages.
Submitted by Godwill Tetah, on July 08, 2019
Hi! Welcome. Today, we are going to look at EJS partials. EJS Partials help us avoid repetition of the same code on several web pages.
For example, you may want the same header for several web pages.
EJS partials work like EJS layouts too in creating a single fix content on a web page.
Take Note! You should have Node.js installed in your before you can start using EJS in this article.
To download Node JS, visit nodejs.org, then install.
* BASIC NODE.JS/EXPRESS KNOWLEDGE REQUIRED
To begin, ensure you have EJS and express installed via npm.
To install EJS, simply open a terminal/command prompt and type the following command:
npm install ejs
or
npm install ejs –save
Unlike EJS Layouts, EJS partials can work without the express-ejs-layouts module. EJS partials apply in cases like creating objects like header, footer, div.
NB: For a web page to contain the partial, it must be connected to each partial via a line of code, unlike layouts which apply everywhere.
* To know about layouts, read our article on EJS LAYOUTS
Let's see an example for,
Open your text editor and type the following code, save as app.js.
var express = require('express');
var ejs = require('ejs');
var app = express();
app.set('view engine', 'ejs');
app.get("/", function(req, res) {
res.render("home");
});
app.get("/about", function(req, res) {
res.render("about");
});
app.listen(3000, function() {
console.log("server is listening!!!");
});
In our code above, we have included the express-ejs-layouts module and have also created a new route.
Now, let's create our ejs files:
We created 2 routes and have rendered both routes to an ejs file.
Now let's create our ejs files.
Open a text editor and type the following code, save as home.ejs
<%- include('partials/partial') %>
<h4> Home Page</h4>
The home.ejs file has a link to the partial.ejs file which serves as the partial.
Open a text editor and type the following code, save as about.ejs
<h3> About US</h3>
Finally, initiate the app.js file with node app.js in a terminal and view the port in a browser.
localhost:3000 and localhost:3000/about
Output
The about page doesn't display the partial because it has no link to it.
Thanks for coding with me! Feel free to drop a comment or question.