Express.js / Express.js with Template Engines

Using Partials and Layouts in Template Engines

Partials and layouts are powerful features of most template engines that allow for code reuse. This tutorial will guide you through creating and using partials and layouts in your…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers using template engines like EJS, Pug, and Handlebars to render dynamic views.

Using Partials and Layouts in Template Engines

1. Introduction

In this tutorial, we're going to learn about using partials and layouts in template engines.

Partials are reusable blocks of code that can be included in multiple templates. This helps in reducing code duplication and improving maintainability. Layouts, on the other hand, are the skeleton or structure of the page that stays constant across different pages, like headers, footers, or navigation bars.

By the end of this tutorial, you will have learned:
- What are partials and layouts
- How to create and use partials and layouts

Prerequisites:
- Basic understanding of HTML
- Some experience with a programming language
- Familiarity with the concept of templates

2. Step-by-Step Guide

Partials

Partials are like functions, they make large websites easier to maintain. You don't have to repeat the same code in multiple locations. If you need to make a change, you make it in one place, and it propagates to all the instances.

Here's how you can create a partial. We'll use Handlebars.js for this example:

// This is the partial, a small reusable piece of code
Handlebars.registerPartial('myPartial', '<p>This is a partial</p>');

And here's how you can use it:

<div>
  {{> myPartial}}
</div>

Layouts

A layout is a high-level structure that houses different views. It often includes components like headers, footers, and sidebars.

Here's a simple example using the Express.js framework and the EJS template engine:

// This is your layout file (layout.ejs)
<html>
  <head>
    <title>My Website</title>
  </head>
  <body>
    <%- body %>
  </body>
</html>

In the above code, <%- body %> is where your views will be injected.

3. Code Examples

Here are some practical examples:

  1. Creating and using a partial:
// Registering a partial
Handlebars.registerPartial('link', '<a href="{{url}}">{{text}}</a>');

// Using the partial
var template = Handlebars.compile('<div>{{> link }}</div>');
console.log(template({url: 'http://google.com', text: 'Google'}));
// Output: <div><a href="http://google.com">Google</a></div>
  1. Creating and using a layout:
<!-- layout.ejs -->
<html>
  <head>
    <title>My Website</title>
  </head>
  <body>
    <header>
      <h1>Welcome to my website!</h1>
    </header>
    <%- body %>
    <footer>
      <p>Copyright 2021</p>
    </footer>
  </body>
</html>

<!-- index.ejs -->
<p>This is the home page</p>

<!-- server.js -->
app.get('/', function (req, res) {
  res.render('index', {layout : 'layout'});
});

In the above example, when you visit the home page, you will see the header and footer from the layout, and the content from index.ejs.

4. Summary

We have covered how to create and use partials and layouts in template engines. They are powerful features that help you create reusable blocks of code and maintain the structure of your website.

Next, you could explore different template engines and their unique features. You could also learn more about Express.js, a popular web application framework that works well with various template engines.

5. Practice Exercises

  1. Create a partial for a navigation bar and use it in multiple pages.
  2. Create a layout that includes a header, a footer, and a sidebar. Use this layout in a home page and an about page.
  3. Modify the layout from exercise 2 to include a different sidebar for the about page.

Remember, practice is key when learning a new concept, so try to complete these exercises without referring back to the tutorial. Good luck!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help