Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Responsive image macro
{% macro responsiveImage(file, sizes, options) %}
{# settings #}
{% set pixel = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==' %}
{# logic #}
{% if file is defined and sizes is defined and sizes is iterable %}
{% if sizes|first is iterable or sizes|first is null %}
{# array of transforms #}
<picture class="{{options.class ?? null}}">
{% for media, settings in sizes %}
{% set url = settings is not null ? file.getUrl(settings) : pixel %}
<source media="{{media}}" srcset="{{url}}"></source>
{% endfor %}
{% set urlFallback = sizes|first is not null ? file.getUrl(sizes|first) : pixel %}
<img src="{{urlFallback}}" alt="{{options.alt ?? null}}">
</picture>
{% else %}
{# single transform #}
<img src="{{file.getUrl(sizes)}}" alt="{{options.alt ?? null}}" class="{{options.class ?? null}}">
{% endif %}
{% endif %}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.