Skip to content

Instantly share code, notes, and snippets.

@M-Drummond
Created March 26, 2019 22:54
Show Gist options
  • Save M-Drummond/9c29081d74e198383b729d737e32787a to your computer and use it in GitHub Desktop.
Save M-Drummond/9c29081d74e198383b729d737e32787a to your computer and use it in GitHub Desktop.
Craft + imager data-srcset macro.
{% macro srcSet(image) %}
{# Lazyload + WebP enable iamge tag. #}
{# Create image sizes in JPG format #}
{% set jpg = [
{ width: 1080 , format: 'jpg' },
{ width: 900 , format: 'jpg'},
{ width: 720 , format: 'jpg'},
{ width: 480 , format: 'jpg' }
] %}
{% set srcsetJpg = craft.imager.transformImage(image, jpg) %}
{# Check for WebP support and create images if available. #}
{% if craft.imager.serverSupportsWebp() %}
{% set webp = [
{ width: 1080 , format: 'webp' },
{ width: 900 , format: 'webp'},
{ width: 720 , format: 'webp' },
{ width: 480 , format: 'webp' }
] %}
{% set srcsetWebp = craft.imager.transformImage(image, webp) %}
{% endif %}
<picture>
{# Create a <source> element with the set of webP images. This will only be used in browsers that like webp. #}
{% if webp is defined %}
<source sizes="100vw" srcset="{{ craft.imager.srcset(srcsetWebp) }}" type="image/webp">
{% endif %}
{# Create the standard JPG using the smallest availabe element as SRC, with the srcset of JPGs for all browsers. #}
<img class="lazyload" src="{{ srcsetJpg[3].url }}" sizes="100vw" srcset="{{ craft.imager.srcset(srcsetJpg) }}" alt="{{ image.title }}" height="auto" width="100%">
</picture>
{% endmacro%}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment