Skip to content

Instantly share code, notes, and snippets.

@ryuran
Created October 28, 2016 09:29
Show Gist options
  • Select an option

  • Save ryuran/471a35b7bfe433dc753e1d05bd5cca0a to your computer and use it in GitHub Desktop.

Select an option

Save ryuran/471a35b7bfe433dc753e1d05bd5cca0a to your computer and use it in GitHub Desktop.
Twig RWD img Macro
{##
# Display img
#
# @param string src [required]
# @param string default [required]
# @param string alt [optional]
# @param bool lazyload [optional]
#
# @param array formats [optional] Array string (image format)
# @param string|array sizes [optional]
#
# @param string|array classes [optional]
# @param string attributes [optional]
#}
{% macro img(src, default, formats = [], alt = '', lazyload = false, classes = '', attributes = '', sizes = '100vw') %}
{% set srcset = [] %}
{% for format in formats %}
{% set srcset = srcset|merge([src|image_format(format) ~ ' ' ~ format|split('x')[0] ~ 'w']) %}
{% endfor %}
{% set srcset = (srcset is empty) ? src|image_format(default) : srcset %}
<img class="{{ classes|join(' ') }}{{ lazyload ? ' lazyload'}}"
src="{{ src|image_format(default) }}"
{% if lazyload %}
srcset="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
data-sizes="auto"
{% else %}
sizes="{{ sizes|join(', ') }}"
{% endif %}
{{ lazyload ? 'data-' -}}srcset="{{ srcset|join(', ') }}"
alt="{{ alt }}"
{{ attributes|raw }} />
{% endmacro %}
{##
# Display picture
#
# create a picture with sources for diferents media-queries
# use macro `img`
#
# @TODO: maybe usefull but not now,
#}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment