Hugo responsive image srcsets

How to render picture tag images in Hugo with custom render-image.html layout.

slurpie

What is hugo?

Hugo is a static site generator written in Go. One can write content in markdown and render HTML using simple HTML templates.

What are responsive images?

Responsive images are images on a website that differ based on screen size or device properties. One popular method in HTML5 to serve responsive images is the <picture> tag.

<picture>
    <!-- image source for different format types -->
    <source srcset="/assets/1.png" type="image/png">
    <source srcset="/assets/1.webp" type="image/webp">
    <!-- img tag with fallback src -->
    <img loading="lazy" src="/assets/1.png" alt="My image">
</picture>

In Hugo we can use a custom layout partial to handle rendering of images to include source sets.

How to implement picture tag

Create a custom layout inside your Hugo theme or layouts folder.

/themes/<your-theme>/layouts/_default/_markup/render-image.html

Inside the partial you can access images as they get processed by Hugo when reading your markdown content.

<p class="markdown-image">
    <picture>
        {{ $url := safeURL .Destination }}
        {{ $image_ext := path.Ext $url }}
        <source srcset="{{ $url }}" type='image/{{replace $image_ext "." ""}}'>
        {{ if or (eq $image_ext ".png") (eq $image_ext ".jpg") }}
        {{ $webpDestination := strings.Replace .Destination $image_ext ".webp" }}
        {{ if (fileExists ( printf "/static%s" $webpDestination )) }}
        <source srcset="{{$webpDestination | safeURL }}" type="image/webp">
        {{ end }}
        {{ end }}
        <img loading="lazy" src="{{ $url }}" alt="{{ .Text }}" {{ with .Title}} title="{{ . }}"{{ end }} />
    </picture>
</p>

The above partial will include webp sources if they exist for png images. You can extend this to include more content types or sizes.

Converting images to webp

Use the webp tool to convert png and jpeg images into webp format.

cwebp assets/1.png -q 70 -o assets/1.webp