Brian Wagner | Blog

Hugo: Options for Managing Image Files

Mar 18, 2022 | Last edit: Mar 18, 2022

Static site generators like Hugo offer a lot of whiz-bang advances over the past generation of making websites. Tooling for rapid builds, efficient patterns for managing content. But in some corners of Hugo, the patterns are the same ones used long ago for building simple HTML websites.

Images are one area where I’m reminded of old techniques that I first learned at the start of my career.

It’s helpful to remember that, in its simplest form, a website is a collection of HTML documents and other files that live on a web server. These files are organized into directories and subdirectories. References to these files can be made using absolute paths, (e.g. /index.html) or paths relative to the current point (e.g. new-page.html). We do similar things when working with files in a terminal environment.

Let’s extend this to managing images in Hugo.

Option One

One recommendation in Hugo is to put all page resources, like images and Javascript files, into a directory called “static” at the root of the project. Then, we can reference these files using absolute paths.

So imagine we have a piece of content with this filepath: content/articles/great-article.md.

---
title: "A great article title"
type: article
---
...
 
![Image alt text](/great-article.jpg)

It doesn’t matter where this HTML file is located. We can change the path later. The absolute path to the image file will always work.

One downside of this approach is that it can become difficult to manage large numbers of images. Also, it’s not apparent which images are used on which pages; the page structure is broken.

Option Two

This option is helpful to maintain the page structure. Also it calls back to the pattern of using subdirectories to hold all of a page’s resources.

A page in Hugo can be created in one of two ways:

  • create a new file in the relevant directory, such as content/articles/great-article.md
  • or, create a subdirectory called content/articles/great-article, which contains a file called index.md

Next we can drop the images and other resources for the page into that same directory. And reference those files like so:

---
title: "A great article title"
type: article
---
...
 
![Image alt text](great-article.jpg)

Note there is no leading slash, as we’re using relative paths.

To further organize, add another subdirectory called images/ and drop the image files in there. And our content looks like this:

![Image alt text](images/great-article.jpg)
|—— content
  |—— articles
    |—— pretty-ok-article.md
    |—— great-article
      |—— index.md
      |—— images
        |—— great-article.jpg