Skip to content

Instantly share code, notes, and snippets.

@samlester
Last active November 4, 2015 15:20
Show Gist options
  • Save samlester/eae9c40b1e90fde7aa2e to your computer and use it in GitHub Desktop.
Save samlester/eae9c40b1e90fde7aa2e to your computer and use it in GitHub Desktop.
Retina image macros for Craft CMS
{% macro srcset(image, desiredWidth, desiredHeight) %}
{%- spaceless %}
{# Calculate the widths #}
{% set width = desiredWidth %}
{% set width2x = desiredWidth * 2 %}
{# Calculate the heights if they exist #}
{% if desiredHeight %}
{% set height = desiredHeight %}
{% set height2x = desiredHeight * 2 %}
{% else %}
{% set height = null %}
{% set height2x = null %}
{% endif %}
{# Is this a large enough image to make a 2x version? #}
{% if image.width > width2x and image.height > height2x %}
{% set isLarge = true %}
{% else %}
{% set isLarge = false %}
{% endif %}
{# Output the src and srcset attributes #}
{% if isLarge %}
{% set image1x = image.getUrl({ width: width, height: height }) %}
{% set image2x = image.getUrl({ width: width2x, height: height2x }) %}
src="{{ image1x }}"
srcset="{{ image1x }} 1x, {{ image2x }} 2x"
{% else %}
src="{{ image.getUrl({ width: width, height: height }) }}"
{% endif %}
{% endspaceless -%}
{% endmacro %}
{% macro bg(image, desiredWidth, desiredHeight) %}
{%- spaceless %}
{# Calculate the metrics #}
{% set width = desiredWidth %}
{% set width2x = desiredWidth * 2 %}
{% set height = desiredHeight %}
{% set height2x = desiredHeight * 2 %}
{# Is this a large enough image to make a 2x version? #}
{% if image.width > width2x and image.height > height2x %}
{% set isLarge = true %}
{% else %}
{% set isLarge = false %}
{% endif %}
{# Output the src and srcset attributes #}
{% if isLarge %}
{% set image1x = image.getUrl({ width: width, height: height }) %}
{% set image2x = image.getUrl({ width: width2x, height: height2x }) %}
style="background-image: url({{ image1x }}); @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) { background-image: url({{ image2x }}); }"
{% else %}
style="background-image: url({{ image1x }});"
{% endif %}
{% endspaceless -%}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment