Skip to content

Instantly share code, notes, and snippets.

@ivanchromjak
Created August 28, 2023 14:08
Show Gist options
  • Save ivanchromjak/8ecec06813687532bb38b86dff2260b6 to your computer and use it in GitHub Desktop.
Save ivanchromjak/8ecec06813687532bb38b86dff2260b6 to your computer and use it in GitHub Desktop.
{{ $imageSrc := .image | default "" }}
{{ $image := resources.Get $imageSrc }}
{{ if $image }}
{{ $alt := .alt | default $image.Title }}
{{ $loading := .loading | default "lazy" }}
{{ $class := .class | default "w-full" }}
{{ $sizes := .sizes | default "100vw" }}
{{ $itemprop := .itemprop | default "" }}
{{ if or (eq $image.MediaType.SubType "svg") (eq $image.MediaType.SubType "gif") }}
<img
src="{{ $image.RelPermalink }}"
alt="{{ $alt }}"
loading="{{ $loading }}"
class="{{ $class }}"
{{ if $itemprop }}itemprop="{{ $itemprop }}"{{ end }}
/>
{{ else }}
<picture>
<source type="image/webp"
srcset="
{{- $imageWidths := split "320,640,720,1512,2160,2808,3024" "," -}}
{{- range $index, $width := $imageWidths -}}
{{- $webpResize := printf "%sx webp q100" $width -}}
{{- $webpSrcset := printf "%s %sw" ($image.Resize $webpResize).RelPermalink $width -}}
{{- $webpSrcset -}}
{{ if lt $index (sub (len $imageWidths) 1) }}, {{ end }}
{{- end -}}
">
<img
src="{{ ($image.Resize "400x").RelPermalink }}"
srcset="
{{- range $index, $width := $imageWidths -}}
{{- $resize := printf "%sx" $width -}}
{{- $srcset := printf "%s %sw" ($image.Resize $resize).RelPermalink $width -}}
{{- $srcset -}}
{{ if lt $index (sub (len $imageWidths) 1) }}, {{ end }}
{{- end -}}
"
sizes="{{ $sizes }}"
alt="{{ $alt }}"
width="{{ $image.Width }}"
height="{{ $image.Height }}"
loading="{{ $loading }}"
class="{{ $class }}"
{{ if $itemprop }}itemprop="{{ $itemprop }}"{{ end }}
/>
</picture>
{{ end }}
{{ end }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment