Skip to content

Instantly share code, notes, and snippets.

@Chrisedmo
Last active November 14, 2016 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chrisedmo/55d09e12cb60b95067b2694eac60edef to your computer and use it in GitHub Desktop.
Save Chrisedmo/55d09e12cb60b95067b2694eac60edef to your computer and use it in GitHub Desktop.
#CraftCMS: SRCset Macro
{# can define custom sizes, if required #}
{% set outputWidths = [580, 690, 768] %}
{% set aspectRatio = (3/5) %}
{{ srcset(entry.image, outputWidths, aspectRatio) }}
{% 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