Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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