Created
March 11, 2020 20:47
-
-
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
This file contains 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 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 -%} |
This file contains 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 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