I built a website using Hugo, but I've been facing persistent image caching problems. Every time I update an image, I need to ask users to clear their browser cache to see the new images, which is not ideal.
I recently found an insightful article on caching images in Hugo
, https://kmitov.com/posts/classic-challenge-new-tool-addressing-browser-image-caching-issues-with-hugo-fingerprinting/ that offered solutions for this issue.
As suggested, I have created a file entitled render-image.html
under layouts/_default/_markup
folder and added below code
<!-- layouts/_default/_markup/render-image.html -->
{{/* Gets a resource object from the destination of the image that is parent-with-child.png */}}
{{/* The parent-with-child.png image is specified in the markdown and must be available in the */}}
{{/* asset folder */}}
{{ $image := resources.GetMatch .Destination }}
{{/* Calculate the fingerprint, add it to the name and get the Permalink is the full URL of the file */}}
{{ $image := ($image | fingerprint).Permalink }}
<img src="{{ $image }}"/>
Now, I am getting below error
template: _default/_markup/render-image.html:9:23: executing "_default/_markup/render-image.html" at : error calling fingerprint: can not be transformed
Any tips or recommendations on how to ensure updated images are reflected without manual cache clearing?
Note: I am using below theme
https://themes.gohugo.io/themes/mainroad/
I tried adding render-image.html
under themes
folder as well, but no luck
Unfortunately, you cannot use the image render hook to transform images, as indicated in the Hugo documentation.
Note that the embedded image render hook does not perform image processing. Its sole purpose is to resolve Markdown image destinations.
Several options:
A) If you want a Hugo solution using the image render hook, an alternative could be to create a random string that you would add after the end of the image file, which would look like that: imagefile.jpg?randomstring
. That might trigger a refresh on some browsers, but not on all.
{{ $seed := now.Unix }}
{{ $exp := printf "%.10s" (sha256 $seed) }}
<img src="{{ .Destination }}?{{ $exp }}"/>
B) You can use your code in a shortcode, which will allow you to use image processing. Instead of calling your image like this in the MD file:
![](/folder/my-image.png)
You would call a shortcode:
{{< myprocessor "/folder/my-image.png" >}}
C) Two other alternatives are available on this question: