Creating a Shared Partial File in a Hugo Project for Term and List Pages

Published: 2022 June 08

software development web development static site generator Hugo Hugo theme

Background

This project is built with Hugo and uses the Minimal Hugo theme.

This post is part of an ongoing effort to tailor the theme over time.

Objective

In a previous post we updated the list template so that it worked as intended for all sections and subsections.

The terms template, however, which generates pages like the tags page, used redundant code that still reflected the original interface.

In this post we’ll create a new list-page partial template file with the code from the previously updated list template. We’ll then update both the list and terms templates to reference that new list-page partial template file in order to reduce redundant code and so that both types of pages have a consistent UI.

Building the solution

Step 1: Building the new partial template

First, we’ll create the new list-page partial template file in the /layouts/partials/ directory.

We’ll populate it with most of the code from the updated list template:

<!-- INCLUDE THIS LINE AT THE TOP SO THE PAGINATOR CORRECTLY SETS THE PAGINATION VALUE: {{ range (.Paginator 1000).Pages }} {{ partial "list-item" . }} {{ end }} -->

<main>

    <h2>{{ .Title }}</h2>
    <h5>{{ .Paginator.TotalNumberOfElements }} total posts</h5>
    <hr>

    {{ range (.Paginator 1000).Pages }}
        {{ partial "list-item" . }}
    {{ end }}

    <hr>

</main>

{{ partial "paginator" . }}

Step 2: Updating the existing templates

Next, we’ll update both the list and terms templates to reference the new list-page partial template file.

For both templates, the update is straightforward:

{{ partial "header" . }}

{{ partial "list-page" . }}

{{ partial "footer" . }}

Conclusion

Now, both of our list-like templates reference the same code and produce the desired output.

Copying Directory Structure With a Bash Script - With Help From ChatGPT AI

Published: 2024 January 22

Backing Up Git Config Values With a Bash Script

Published: 2023 August 25

Backing Up Visual Studio Code (VS Code) Settings and Extensions With a Bash Script

Published: 2022 November 09