Dynamically generating responsive images with Timber’s resize filter and the srcset attribute
Timber has loads of useful filters built in which can make all kinds of jobs much easier. One of those jobs is resizing and cropping images, for which we can use the resize filter. The syntax is simple, as with all things Twig – we simply add the filter to our image source, passing through a width or height to resize or both to crop.
The following example will resize the image to a width of 300px while retaining its aspect ratio:
{{ item.src|resize(300) }}
The following example will resize the image to a height of 300px while retaining its aspect ratio:
{{ item.src|resize(0, 300) }}
The following example will crop the image to a width and height of 300px:
{{ item.src|resize(300, 300) }}
We can then define multiple sizes and pass these into a srcset attribute to make sure we’re serving a suitable image size based on the device viewport. This is especially important for mobile devices who don’t need to download and display a full HD hero image on a 320px wide screen.
The following example defines three sizes, one for mobile, tablet and desktop – devices with a viewport width of up to 480px will get the 480px wide image and so on.
srcset="{{ item.src|resize(480) }} 480w, {{ item.src|resize(1280) }}
1280w, {{ item.src|resize(1920) }} 1920w"
If you’re new to srcset or want to delve into it a bit deeper, CSS Tricks’ article is a good read.
Filed under: Development insights
Topics: srcset, Timber, Twig, WordPress
Got an idea for a project?
Need a website? Web-enabled software to streamline your business? Just some advice?