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

slurpie

Why do this?

For performance reasons. Using src-sets with image tags means user only get the images they need. This is an important consideration along with other performance tricks such as reducing DOM size and using lazy loading.

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 tag.

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.

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

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.