I come from a WordPress background, so I'm attempting to create responsive images the way I'm accustomed to with WordPress. Perhaps that's the wrong approach, I'm not sure.
In WordPress I would define five images size: thumbnail
, medium
, medium_large
, large
, XL
and I would specify a width for each. Typically I would define the widths as 414
, 768
, 1024
, 1600
and 1920
pixels respectively. For the sizes
attribute I would specify this manually on an image-by-image basis.
Outputting an image would look like this:
<img src="<?php echo wp_get_attachment_image_url( $attachment_id, 'large' ); ?>"
srcset="<?php echo wp_get_attachment_image_srcset( $attachment_id ); ?>" />
The above would output all 5 image sizes to the srcset
attribute.
So, back to Craft. I have setup 5 asset transforms under Settings
using the same handles as above. I believe you can also set these up progmatically too.
I can then output each of my image sizes in the following way:
{% set image = entry.aboutImage.withTransforms(['thumbnail', 'medium', 'mediumLarge', 'large', 'xl']).first() %}
<img src="{{ image.getUrl('medium') }}" alt=""
srcset="{{ image.getUrl('xl') }} {{ image.getWidth('xl') }}w,
{{ image.getUrl('large') }} {{ image.getWidth('large') }}w,
{{ image.getUrl('mediumLarge') }} {{ image.getWidth('mediumLarge') }}w,
{{ image.getUrl('medium') }} {{ image.getWidth('medium') }}w,
{{ image.getUrl('thumbnail') }} {{ image.getWidth('thumbnail') }}w"
width="{{ image.getWidth() }}" height="{{ image.getHeight() }}" />
Whilst this works okay, it's kind of cumbersome to repeat this for every image. Also, if the user uploads a very small image then I'm guessing it won't be available in all sizes.
I noticed that there is also this method:
{{ asset.getImg({ width: 300, height: 300 }, ['1.5x', '2x', '3x']) }}
However I'd like to do the following, which doesn't work:
{{ asset.getImg({ width: 300, height: 300 }, ['thumbnail', 'medium', 'mediumLarge', 'large', 'xl']) }}
I've read about macros
but so far haven't really been able to fathom out how I'd achieve the above using a macro, or it it's necessary.