Last active
November 14, 2016 16:46
-
-
Save Chrisedmo/55d09e12cb60b95067b2694eac60edef to your computer and use it in GitHub Desktop.
#CraftCMS: 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
{# can define custom sizes, if required #} | |
{% set outputWidths = [580, 690, 768] %} | |
{% set aspectRatio = (3/5) %} | |
{{ srcset(entry.image, outputWidths, aspectRatio) }} |
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, outputWidths, aspectRatio) %} | |
{# setup #} | |
{%- set outputWidths = outputWidths | default([640, 1024, 1600]) -%} | |
{%- set srcset = [] -%} | |
{# if output width is smaller than or equal to the original image width #} | |
{%- for outputWidth in outputWidths -%} | |
{%- if outputWidth <= image.width -%} | |
{%- if aspectRatio -%} | |
{%- set transformOptions = { width: outputWidth, height: outputWidth * aspectRatio } -%} | |
{%- else -%} | |
{%- set transformOptions = { width: outputWidth } -%} | |
{%- endif -%} | |
{%- set srcset = srcset | merge([image.url(transformOptions) ~ ' ' ~ outputWidth ~ 'w']) -%} | |
{%- endif -%} | |
{%- endfor -%} | |
{# output srcset #} | |
{{- srcset | join(', ') -}} | |
{% endmacro %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment