Merge new blogPhoto shortcode into 'master'

See merge request patek-devs/patek.cz!9
This commit is contained in:
Vojtěch Káně 2020-05-04 12:17:57 +00:00
commit d10218c320

View File

@ -0,0 +1,51 @@
{{- /*
Usage:
{{< blogPhoto "filename_relative_to_page.ext" "Alt text" >}}
or
{{< blogPhoto src="filename_relative_to_page.ext" alt="Alt text" >}}
where possible named params are:
* src - path to the image in page bundle
* alt - textual description of the image, the <img> alt attribute
* caption (optional) - the caption displayed under the image, defaults to `alt`. Set to false to disable caption rendering
*/ -}}
{{- $imageName := false -}}
{{- $alt := false -}}
{{- if .IsNamedParams -}}
{{- $imageName = .Get "src" | default nil -}}
{{- $alt = .Get "alt" | default nil -}}
{{- else -}}
{{- $imageName = .Get 0 -}}
{{- $alt = .Get 1 -}}
{{- end -}}
{{- if (eq $imageName nil) }}{{ errorf "Missing image name in %s" .Position }}{{ end -}}
{{- if (eq $alt nil) }}{{ errorf "Missing alt for image %s in %s" $imageName .Position }}{{ end -}}
{{- $caption := cond (eq (.Get "caption") false) false (default $alt (.Get "caption")) -}}
{{- $img := .Page.Resources.GetMatch $imageName | default nil -}}
{{- if (eq $img nil) }}{{ errorf "Image %s not found in %s" $imageName .Position }}{{ end -}}
{{- $sizes := slice (slice 640 360 50) (slice 1280 720 50) (slice 1920 1080 50) -}}
{{- $srcset := slice -}}
{{- $largest := false -}}
{{- range $sizes -}}
{{- if (or (gt $img.Width (index . 0)) (gt $img.Height (index . 1))) -}}
{{- $resized := $img.Fit (printf "%dx%d q%d" (index . 0) (index . 1) (index . 2)) -}}
{{- $srcset = $srcset | append (printf "%s %dw" $resized.RelPermalink (index . 0)) -}}
{{- $largest = $resized -}}
{{- end -}}
{{- end -}}
{{- if (lt (len $srcset) (len $sizes)) -}}
{{- $compressed := $img.Fit (printf "%dx%d q90" $img.Width $img.Height) -}}
{{- $srcset = $srcset | append (printf "%s %dw" $compressed.RelPermalink $compressed.Width) -}}
{{- $largest = $compressed -}}
{{- end -}}
<figure>
<img src="{{ $largest.RelPermalink }}" alt="{{ $alt }}" srcset="{{ delimit $srcset ", " }}">
{{ if (ne $caption false) }}<figcaption>{{ $caption }}</figcaption>{{ end }}
</figure>