Nearby lessons
10 of 14π¦ How To Share Common Code in Multiple Pages in Express JS | EJS Template Includes
π What is Code Reuse?
π‘ Understanding Common Code Reuse in Express.js (EJS)
In real-world applications, multiple pages often share the same navigation bar, footer, sidebar, or other repeated UI blocks. Instead of rewriting this code on every page, EJS allows you to include common files and reuse them easily.
This makes your code cleaner, reduces repetition, and simplifies future updates β update once, and all pages reflect the change!
π Step 1: Project Folder Structure
Create the following folder and file structure inside your project:
π project-folder
β£ π views
β β£ π home.ejs
β β£ π about.ejs
β β£ π contact.ejs
β β π common
β β£ π header.ejs
β β π footer.ejs
β π index.js
βοΈ Step 2: Express Setup (index.js)
In your main Express file, set EJS as the view engine and render pages normally:
Example03
Loading editorβ¦
π§± Step 3: Create EJS Pages & Include Common Header and Footer
Each page includes header.ejs and footer.ejs using the EJS include feature:
Example04
Loading editorβ¦
π How It Works
- π EJS
includeallows reusing common UI parts across multiple pages. - π§©
header.ejsandfooter.ejsact as shared components. - π
home.ejs,about.ejs, andcontact.ejsinclude these common sections. - π Updating navigation or footer once updates all pages automatically.
- π§Ή Keeps your project clean, structured, and easy to maintain.
π§ Test Your Knowledge
5 QuestionsProgress: 0 / 5