Generating image sizes in Hugo as a dictionary

While looking at ways to generate different image sizes as a dictionary that Hugo templates and Fuse JS can digest for search via a JSON file, chatGPT suggested the following partial.

{{- $images := dict -}}
{{- with or (.Resources.GetMatch "featured.*") (resources.GetMatch "fallback.*") }}
  {{- $s := .Process "fill 350x350 webp TopLeft" }}
  {{- $m:= .Process "fill 480x480 webp TopLeft" }}
  {{- $l := .Process "fill 628x628 webp TopLeft" }}
  {{- $images = dict
        "s" (dict "src" $s.Permalink "w" $s.Width "h" $s.Height "type" $s.MediaType.Type)
        "m" (dict "src" $m.Permalink "w" $m.Width "h" $m.Height "type" $m.MediaType.Type)
        "l" (dict "src" $l.Permalink "w" $l.Width "h" $l.Height "type" $l.MediaType.Type)
  -}}
{{- end }}

{{- return $images -}}

Then calling the partial in another partial or layout as such–

{{/* call your partial and store the returned dict */}}
    {{- $images := partial "thumbnails.html" . -}}

    {{ with $images }}
    <picture>
      <source srcset="{{ .s.src }}" media="(min-width: 1024px)" type="{{ .s.type }}">
      <source srcset="{{ .m.src }}" media="(min-width:640px)" type="{{ .m.type }}">
      <img src="{{ .l.src }}" width="{{ .l.w }}" height="{{ .l.h }}" alt="{{ $.Title }}" alt="">
    </picture>
    {{ end }}

Typically with Crop and Fill you would want to use “Smart” (the default) or “Center”, but what you have may be by design.

1 Like

It is! The design I have for featured images crops out the logo on the right side and retains text on the left of the image on list pages. I found out TopLeft positions this text nicely!

1 Like