Insert Images in Hugo and Automatically Clear `public` Folder



When I updated my website, I faced some technical issues: how to insert images into posts and how to automatically clear the public folder. Now I have solutions to both challenges and would like to share them with you.

Insert Images

To insert images into posts, I researched online resources and found two important considerations: the correct location for images and the method to load them.

First, there are two methods to store images in your project. The first method is to place images in the same folder as the post’s index.md file, so they are only loaded by that post. For example:

..
|
└───content
    |   _index.md
    |
    └───posts
        |   ...
        |
        └───time_management_with_Apple's_App
            index.md
            img1.png
            img2.png

The second method is to place images in the static folder, making them accessible to every page. For example: /static/images/logo.png.

Second, after placing images in the correct location, you can load them using three methods:

  1. Markdown style: Use ![description](path/to/image). For a page bundle, write ![daily tasks](img1.png).

  2. Figure shortcode (my preferred method): Hugo’s built-in feature. Example: {{ < figure src="img1.png" title="Daily tasks" alt="" width="600" class="center" >}}. (⚠️Please remove the blank between { and < when you use it.) This method offers more control over styling through CSS or SCSS. I used an AI tool to create custom shortcode templates and stylesheets.

  3. Page Resources: A more advanced method that I haven’t explored yet.

I hope this helps you successfully display images in your posts. If you encounter problems, check your image paths and clear your cache using hugo --gc.

Clean The public Folder

After testing many methods for inserting images, I accumulated many outdated pages in the public folder. Rather than manually deleting them, I wanted an automatic solution. I found an elegant method from essesoul1: simply add one line to hugo.toml:

cleanDestinationDir = true

Finally, I’d like to thank the authors I referenced, especially Brain Build, who compiled helpful resources2 about inserting images in Hugo.