Alternate webp image - AMP conform

I got this shortcode from @jmooring (big thanks!) - works great!

But right now I am experimenting with AMP and the <picture> tag is not allowed. So here is a AMP conform method.

In your *.md page:
{{< picture-amp path="images/myimage.png" alt="My image" width="500" height="150" >}}

layouts/shortcodes/picture-amp.html

{{- $path := .Get "path" -}}
{{- $alt := .Get "alt" -}}
{{- $width := .Get "width" -}}
{{- $height := .Get "height " -}}
{{- $msg1 := "The %q shortcode requires a parameter named %q. See %s" -}}
{{- $msg2 := "The resource %q passed to the %q shortcode is not an image. See %s" -}}
{{- $msg3 := "The resource %q passed to the %q shortcode could not be found. See %s" -}}
{{ if not $path }}
  {{ errorf $msg1 .Name "path" .Position }}
{{ end }}

{{- with $i := resources.Get $path -}}
  {{- if eq $i.MediaType.MainType "image" -}}
    {{- if not $width -}}
      {{- $width = $i.Width -}}
    {{- end -}}

    {{- if not $height -}}
      {{- $height = $i.Height -}}
    {{- end -}}

    {{- $j := "" -}}
    {{- $w := "" -}}
    {{- if eq $i.MediaType "image/webp" -}}
      {{- $fitOptions := printf "%vx%v jpg" $width $height -}}
      {{- $j = $i.Fit $fitOptions -}}
      {{- $w = $i -}}
    {{- else if eq $i.MediaType "image/jpeg" -}}
      {{- $fitOptions := printf "%vx%v webp" $width $height -}}
      {{- $w = $i.Fit $fitOptions -}}
      {{- $j = $i -}}
    {{- else -}}

      {{- $fitOptions := printf "%vx%v jpg" $width $height -}}
      {{- $j = $i.Fit $fitOptions -}}
      {{- $fitOptions = printf "%vx%v webp" $width $height -}}
      {{- $w = $i.Fit $fitOptions -}}
    {{- end -}}

    <amp-img alt="{{ $alt }}"
    width="{{ $j.Width }}"
    height="{{ $j.Height }}"
    layout="responsive"
    src="{{ $w.RelPermalink }}">

    <amp-img alt="{{ $alt }}"
    fallback
    width="{{ $j.Width }}"
    height="{{ $j.Height }}"
    layout="responsive"
    src="{{ $j.RelPermalink }}">
    </amp-img>
    </amp-img>

  {{- else -}}
    {{- errorf $msg2 $path $.Name $.Position -}}
  {{- end -}}
{{- else -}}
  {{- errorf $msg3 $path .Name .Position -}}
{{- end -}}
{{- /* chomp */ -}}

It will render to:

<amp-img alt="My image"
    width="500" 
    height="150"
    layout="responsive"
    src="/images/myimage_hud5b8b28af4_213302_500x150.webp">
<amp-img alt="My image"
    fallback
    width="500" 
    height="150"
    layout="responsive"
    src="/images/myimage_hud5b8b28af4_213302_500x150.jpg">
</amp-img>
</amp-img>

To test and show the images the page must have a proper AMP setup.

1 Like