Browse Source

added image partial

Alexander Avery 3 weeks ago
parent
commit
8fa9a9b673
  1. 7
      layouts/_default/single.html
  2. 47
      layouts/partials/image.html

7
layouts/_default/single.html

@ -11,6 +11,13 @@
<h4>Posted: <time datetime="{{ $dateMachine }}">{{ $dateHuman }}</time></h4>
{{ partial "image.html"
(dict
"image" (.Resources.GetMatch "featured")
"alt" .Params.featured.alt
"sizes" (slice 320 480 600 800)
"classes" "shadow featured") }}
{{ .Content }}
{{ partial "terms.html" (dict "taxonomy" "tags" "page" .) }}
{{ end }}

47
layouts/partials/image.html

@ -0,0 +1,47 @@
{{- /*
Renders an image with the given class, alt, and sizes.
@contetx {alt} alt text for the image.
@context {image} the image resource.
@context {sizes} each size to include in the srcset.
@context {classes} classes for the image.
*/}}
{{ $alt := .alt }}
{{ $image := .image }}
{{ $sizes := .sizes }}
{{ $classes := .classes }}
<img class="{{ delimit $classes " " }}"
{{ $srcsetParts := slice }}
{{ $sizesParts := slice }}
{{ $len := len $sizes }}
{{/* Loop through widths to resize images and build attributes */}}
{{ range $index, $width := $sizes }}
{{ $resizeSpec := printf "%dx webp q90" $width }}
{{ $resized := ($image.Resize $resizeSpec) }}
{{ $srcsetParts = $srcsetParts | append (printf "%s %dw" $resized.RelPermalink $width) }}
{{/* Build sizes: media query for all but the last width */}}
{{ if lt $index (sub $len 1) }}
{{ $nextWidth := index $sizes (add $index 1) }}
{{ $sizesParts = $sizesParts | append (printf "(max-width: %dpx) %dpx" $nextWidth $width) }}
{{ else }}
{{ $sizesParts = $sizesParts | append (printf "%dpx" $width) }}
{{ end }}
{{ end }}
{{/* Set src to the smallest image */}}
{{ $smallestWidth := index $sizes 0 }}
{{ $smallestResizeSpec := printf "%dx webp q90" $smallestWidth }}
{{ $smallest := ($image.Resize $smallestResizeSpec) }}
{{ $src := $smallest.RelPermalink }}
{{/* Output attributes */}}
src="{{ $src }}"
srcset="{{ delimit $srcsetParts ", " }}"
sizes="{{ delimit $sizesParts ", " }}"
alt="{{ $alt }}"
>
Loading…
Cancel
Save