Issue with Duplicated Image Generation in Hugo Partial
I have a partial that generates the same image with multiple sizes (image opt.) using a provided URL, but when I call this partial multiple times with the same URL, Hugo generates multiple copies of the same resized images, leading to redundancy and performance issues.
Here’s an example of how I’m using the partial in my Hugo template:
{{ partial "image" ( dict
"src" "https://some.image.com/sample"
"alt" "alt text"
"sizes" (slice "100x100" "150x150" "200x200")
)
}}
And here’s a simplified version of the image.html
partial:
<!-- image.html -->
{{ $src = .src }}
{{ $class = .src }}
{{ $alt = .src }}
{{ $sizes := default (slice "300x" "600x" "1200x") .sizes }}
{{$r := partial "fetch-image" (dict "src" $src) }}
{{- if $r }}
{{/* Generating resized images */}}
{{ $scaledImages := slice }}
{{ range $index, $size := $sizes }}
{{ $scaledImage := $r.Resize ( printf "%s webp photo" $size)}}
{{ $scaledImages = $scaledImages | append $scaledImage }}
{{ end }}
{{ $sources := slice }}
{{ range $index, $scaledImage := $scaledImages }}
{{ $sources = $sources | append (printf "%s %dw" $scaledImage.RelPermalink $scaledImage.Width) }}
{{ end }}
{{- /* Render image element. */ -}}
<img class="{{ .class }}" alt="{{ .alt }}"
src="{{ (index $scaledImages 0).RelPermalink }}"
srcset="{{ delimit $sources "," }}">
{{- end -}}
I’ve noticed that when I call the partial with the same URL but with different parameters (eg. class, alt) multiple times, Hugo generates new images even though the URLs are identical. This is causing unnecessary image duplication and negatively impacting my site’s performance.
I’ve considered implementing caching or hash-based filenames to solve this issue, but I’m not sure how to go about it within the context of Hugo’s templating system. I’m looking for guidance on the best approach to prevent Hugo from generating duplicated images.
Any advice, code examples, or suggestions would be greatly appreciated. Thank you in advance for your help!
Non-working strategies
PartialCached
As far as I can tell, it seems that Hugo has the ability to generate multiple sites parallel. However, this means that if in the rendering pipeline, there are two sites processing the same image, it will be duplicated.