Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@piotrpog
Created March 11, 2020 20:47
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 piotrpog/74ca9fa830961dc0ad69ae8ada3d8138 to your computer and use it in GitHub Desktop.
Save piotrpog/74ca9fa830961dc0ad69ae8ada3d8138 to your computer and use it in GitHub Desktop.
Placeholder image macro for Craft CMS. More info: http://craftsnippets.com/articles/placeholder-image-macro-for-craft-cms
{%- macro transformOrPlaceholder(image, settings, attributes = {}) -%}
{% if image is not null %}
{% set src = image.getUrl(settings) %}
{% set attributes = attributes|merge({src: src}) %}
{{tag('img', attributes)}}
{% elseif settings.width is defined or settings.height is defined %}
{% set width = settings.width ?? settings.height %}
{% set height = settings.height ?? settings.width %}
{% set src = 'https://placehold.co/'~width~'x'~height %}
{% set attributes = attributes|merge({src: src}) %}
{{tag('img', attributes)}}
{% endif %}
{%- endmacro -%}
{%- macro transformOrPlaceholder(image, settings, attributes = {}) -%}
{# settings #}
{% set placeholderStyle = {
'background-image': 'url(placeholder.jpg)',
'background-position': 'center',
'background-size': 'cover',
} %}
{# logic #}
{% if image is not null %}
{% set src = image.getUrl(settings) %}
{% set attributes = attributes|merge({src: src}) %}
{{tag('img', attributes)}}
{% elseif settings.width is defined or settings.height is defined %}
{% set width = settings.width ?? settings.height %}
{% set height = settings.height ?? settings.width %}
{% set svg = '<svg xmlns="http://www.w3.org/2000/svg" width="'~width~'" height="'~height~'"/>'|url_encode %}
{% set src = 'data:image/svg+xml;charset=utf-8,'~svg %}
{% set attributes = attributes|merge({src: src}) %}
{% set attributes = attributes|merge({style: placeholderStyle}) %}
{{tag('img', attributes)}}
{% endif %}
{%- endmacro -%}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment