Created
March 26, 2019 22:54
-
-
Save M-Drummond/9c29081d74e198383b729d737e32787a to your computer and use it in GitHub Desktop.
Craft + imager data-srcset macro.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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