I am using the render-image.html
with the markup below. How to modify the code to support webp
while providing a fallback to jpeg/jpg
for old browsers/those that don’t support web?
{{ $image := .Page.Resources.GetMatch (printf "%s" (.Destination | safeURL)) }}
{{ $small := $image.Resize "480x" }}
{{ $medium := $image.Resize "768x" }}
{{ $big := $image.Resize "992x" }}
{{ $alt := .PlainText | safeHTML }}
{{ $caption := "" }}
{{ with .Title }}
{{ $caption = . | safeHTML }}
{{ end }}
<figure>
<a href="{{ $image.RelPermalink }}">
<img
sizes="100vw"
srcset="{{ $small.RelPermalink }} 480w, {{ $medium.RelPermalink }} 768w, {{ $big.RelPermalink }} 992w"
src="{{ $image.RelPermalink }}"
width="{{ $image.Width }}"
height="{{ $image.Height }}"
alt="{{ if $alt }}{{ $alt }}{{ else if $caption }}{{ $caption | markdownify | plainify }}{{ else }} {{ end }}"
>
</a>
{{ with $caption }}
<figcaption>{{ . | markdownify }}</figcaption>
{{ end }}
</figure>
FWIW when I do this I use the <picture> element in a layout/shortcode/render-hook. How to use the <picture> element is more of an HTML question rather than a Hugo question IMO.
This option I found in this forum uses the standard markdown image ![image](link here "extra title")
. So I would prefer to keep it that way.
It seems though this code generates a jpg file at the end of the source.
hi @anon44707125
try using the webp fallback like this instead
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg">
</picture>
webp conversion is really easy in Hugo Image Processing | Hugo
all you have to do for webp conversion is to add webp in your shared example;
# your example
{{ $medium := $image.Resize "768x" }}
# modification for webp
{{ $mediumwebp := $image.Resize "768x webp" }}
and then simply use that with .RelPermalink
<picture>
<source srcset="{{ $mediumwebp.RelPermalink }}" type="image/webp">
<source srcset="{{ $medium.RelPermalink }}" type="image/jpeg">
<img src="{{ $medium.RelPermalink }}">
</picture>
this part is the easiest to learn in Hugo with very clear documentation, hope it was helpful
thanks
2 Likes
That works! I just added the media tag for responsive images.
system
Closed
March 17, 2022, 7:47pm
6
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.