Hugo responsive image srcsets

Serve responsive picture tags with custom render-image layout partial in Hugo static site generator.

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

Related content

Javascript email libraries for MailSlurp

Nodemailer alternatives to send and receieve email in code and tests

Fastest way to start a typescript project

Modern typescript tooling has come a long way. See how to setup a new project with TS-Node, TSC, and typeconfig.json.

Fetch error message javascript

Handle response exceptions with Fetch in Javascript

GraphQL API disposable email accounts

How to create real email addresses using GraphQL to send and receive emails in tests and frontend applications.

GraphQL Email API Tutorial

Did you know you can send and receive emails using GraphQL?

Hugo responsive image srcsets

Serve responsive picture tags with custom render-image layout partial in Hugo static site generator.

Ready to dive in?Start building email applications today.