I want avoid unnecessary resizing of image resources that are under a certain size. A simplified version of my current code looks like this:
{{ range $coverIMG }}
{{ $imgFallback := $coverIMG.Resize "1080x q75 jpg photo" }}
{{ $imgLarge := $coverIMG.Resize "2160x q60 webp photo" }}
{{ $imgMedium := $coverIMG.Resize "1080x q75 webp photo" }}
{{ $imgSmall := $coverIMG.Resize "640x q75 webp photo" }}
<div class="o-cover__images-item">
<img class="o-cover__images-item-img" srcset="
{{ if gt $coverIMG.Width 2000 }}{{ $imgLarge.RelPermalink }} {{ $imgLarge.Width }}w,{{ end }}
{{ $imgMedium.RelPermalink }} {{ $imgMedium.Width }}w,
{{ $imgSmall.RelPermalink }} {{ $imgSmall.Width }}w"
width="{{ $imgMedium.Width }}"
height="{{ $imgMedium.Height}}"
src="{{ $imgFallback.RelPermalink }}">
</div>
{{ end }}
As I understand it, the 2160px version will be generated even if I do not use the variable in the scrset
, and even if the original image is smaller (lets say 1080px wide). I have tried wrapping the resizing variable in an if condition, but it causes errors (see below):
{{ range $coverIMG }}
{{ $imgFallback := $coverIMG.Resize "1080x q75 jpg photo" }}
{{ if gt $coverIMG.Width 2000 }}{{ $imgLarge := $coverIMG.Resize "2160x q60 webp photo" }}{{ end }}
{{ $imgMedium := $coverIMG.Resize "1080x q75 webp photo" }}
{{ $imgSmall := $coverIMG.Resize "640x q75 webp photo" }}
<div class="o-cover__images-item">
<img class="o-cover__images-item-img" srcset="
{{ with $imgLarge }}{{ .RelPermalink }} {{ .Width }}w,{{ end }}
{{ $imgMedium.RelPermalink }} {{ $imgMedium.Width }}w,
{{ $imgSmall.RelPermalink }} {{ $imgSmall.Width }}w"
width="{{ $imgMedium.Width }}"
height="{{ $imgMedium.Height}}"
src="{{ $imgFallback.RelPermalink }}">
</div>
{{ end }}
The error is: undefined variable "$imgLarge"
. I was under the impression that a with
would ignore variables if they do not exist or are empty?
EDIT: If anyone want to look at the full source code, it is available here:
Diff: ~rsolvang/hetlankheet-website: Broken conditional resize - sourcehut git
File: ~rsolvang/hetlankheet-website: themes/hetlankheet/layouts/partials/cover.html - sourcehut git