I have a list of image sizes I want to resize an image to, and I don’t want to produce resized images larger than the original image.
Here’s the list of image sizes in my config.toml:
[params]
bodyPhotoWidths = [540, 720, 1080, 1440, 2160, 2880, 3600]
bodyWidthPX = "720"
And here’s the shortcode that resizes the images:
{{/* get file that matches the filename as specified as src="" in shortcode */ -}}
{{ $src := .Page.Resources.GetMatch (printf "*%s*" (.Get "src")) -}}
{{ $imgSrc := "" -}}
{{ $imgSrcSet := slice -}}
{{ $widths := $.Site.Params.bodyPhotoWidths -}}
{{ $body := $.Site.Params.bodyWidthPX | default 720 -}}
{{ range $widths -}}
{{ $srcUrl := (printf "%dx" . | $src.Resize).RelPermalink -}}
{{ if eq $imgSrc "" }}{{ $imgSrc = $srcUrl }}{{ end -}}
{{ if ge $src.Width . -}}
{{ $imgSrcSet = $imgSrcSet | append (printf "%s %dw" $srcUrl .) -}}
{{ end -}}
{{ end -}}
{{ $imgSrcSet = (delimit $imgSrcSet ",\n\t") -}}
<img
src="{{ $imgSrc }}"
{{ with .Get "sizes" }}sizes='{{.}}'{{ else -}}
sizes="(min-width: {{ $body }}px) {{ $body }}px, (max-width: {{ $body }}px) 100vw"
{{ end -}}
srcset="{{ $imgSrcSet }}"
{{ with .Get "alt" }}alt="{{.}}"{{ else }}alt=""{{ end }}
class=imgbody>
This technically works, it only lists images that are smaller than the original image, but it is still creating resized images that are larger than the original image (and simply not printing the urls in HTML). It would be better if we could eliminate the listed image sizes that are larger than the original image and not produce them at all. How would you rewrite this? With range where
? I can’t get the syntax right or something, everything I’ve tried has either resulted in errors or no image sizes being used at all. I imagine something like:
{{ range where $widths "le" $src.Width -}}