squirrel/layouts/partials/components/image.html

90 lines
2.3 KiB
HTML

<!--
id: string
style: string - default empty
url: string
alt: string
caption: string
width: int
height: int
-->
{{ $sizes := slice "320" "640" "960" "1280" }}
{{ $mediaWidthControl := "(max-width: 360px) 320px, (max-width: 680px) 640px, (max-width: 1100px) 960px, 1280px" }}
{{ $id := .id }}
{{ $style := .style }}
{{ $alt := .alt }}
{{ $caption := .caption }}
{{ $width := .width }}
{{ $height := .height }}
{{ $img := .Page.Resources.GetMatch .url }}
{{ if not $img }}
{{ $img = resources.Get .url }}
{{ if not $img }}
{{ $img := resources.GetRemote .url | resources.Copy (path.Join "images" (path.Base .url )) }}
{{ end }}
{{ end }}
{{ with $img }}
{{ $url := .RelPermalink }}
{{ $type := .MediaType.SubType }}
{{ $ext := path.Ext $url }}
{{ $name := path.Base (replace $url $ext "") }}
{{ $dir := path.Dir $url }}
{{ if eq $type "svg" }}
<img
id="{{ $id }}"
class="{{ $style }}"
src="{{ $url }}"
alt="{{ $alt }}"
loading="lazy"
decoding="async"
>
{{ else }}
<picture>
<source
type="image/avif"
srcset="
{{ range $i, $size := $sizes }}
{{ $dir }}/{{ $name }}-{{ $size }}{{ $ext }}.avif {{ $size }}w,
{{ end }}
{{ $url }}.avif {{ $width | default .Width }}w
"
sizes="{{ $mediaWidthControl }}"
/>
<source
type="image/webp"
srcset="
{{ range $i, $size := $sizes }}
{{ $dir }}/{{ $name }}-{{ $size }}{{ $ext }}.webp {{ $size }}w,
{{ end }}
{{ $url }}.webp {{ $width | default .Width }}w
"
sizes="{{ $mediaWidthControl }}"
/>
<img
id="{{ $id }}"
class="{{ $style }}"
width="{{ $width | default .Width }}"
height="{{ $height | default .Height }}"
srcset="
{{ range $i, $size := $sizes }}
{{ $dir }}/{{ $name }}-{{ $size }}{{ $ext }} {{ $size }}w,
{{ end }}
{{ $url }} {{ $width | default .Width }}w
"
src="{{ $url }}"
alt="{{ $alt }}"
loading="lazy"
decoding="async"
>
</picture>
{{ end }}
{{ if $caption }}
<p class="caption">{{ $caption }}</p>
{{ end }}
{{ end }}
{{/* https://www.brycewray.com/posts/2023/05/better-code-image-processing-hugo-render-hook-edition/ */}}