0
0
Expressframework~30 mins

Template partials and layouts in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Template Partials and Layouts in Express
šŸ“– Scenario: You are building a simple website using Express and EJS templates. You want to reuse common parts of your pages like the header and footer, and have a main layout that wraps your content.
šŸŽÆ Goal: Create an Express app that uses EJS templates with a layout and partials for header and footer. Render a home page that uses these partials inside the layout.
šŸ“‹ What You'll Learn
Create a main layout template called layout.ejs with a placeholder for page content
Create partial templates called header.ejs and footer.ejs
Include the header.ejs and footer.ejs partials inside the layout
Render a home page index.ejs that uses the layout and displays a welcome message
šŸ’” Why This Matters
šŸŒ Real World
Web developers often use template partials and layouts to avoid repeating code and keep their HTML organized and maintainable.
šŸ’¼ Career
Understanding how to use layouts and partials in Express with EJS is a common skill required for building scalable web applications.
Progress0 / 4 steps
1
Set up Express app and EJS view engine
Create an Express app in app.js. Set the view engine to ejs using app.set('view engine', 'ejs').
Express
Need a hint?

Use import express from 'express' and then const app = express(). Set the view engine with app.set('view engine', 'ejs').

2
Create layout and partial templates
Create a file views/layout.ejs with HTML structure. Inside it, include the partials header.ejs and footer.ejs using <%- include('header') %> and <%- include('footer') %>. Add a placeholder <%- body %> where page content will go.
Express
Need a hint?

Use EJS syntax <%- include('filename') %> to include partials. Use <%- body %> to insert page content.

3
Create header and footer partials
Create views/header.ejs with a <header> containing a site title inside an <h1>. Create views/footer.ejs with a <footer> containing a copyright notice.
Express
Need a hint?

Write simple HTML inside header.ejs and footer.ejs files with the exact text.

4
Render home page using layout and partials
Create views/index.ejs with a <p> that says Welcome to the home page!. In app.js, add a route for / that renders index.ejs using the layout by passing the content as body.
Express
Need a hint?

Use app.get('/', (req, res) => { res.render('layout', { body: '...' }) }) to render the home page content inside the layout.