Skip to content

Instantly share code, notes, and snippets.

@geoffyuen
Last active November 18, 2019 20:03
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 geoffyuen/6ac5f503081ce7e601a4f6154ca3959a to your computer and use it in GitHub Desktop.
Save geoffyuen/6ac5f503081ce7e601a4f6154ca3959a to your computer and use it in GitHub Desktop.
Image twig with resize and srcset
{% spaceless %}
{#
This Timber twig will output an <img> with srcset x2, alt, width and height
Usage:
`{% include '_img.twig' with { class: "db ma0 center w-100", img: Image(post.acf_image), w: 507, h: 507 } %}`
@params
- img: an Image()
Optional:
- w: width in px to resize to
- h: height in px to resize to
- class: class attribute
- id: id attribute
- alt: alt text, otherwise will use img.title
- letterbox: true? use letterbox to resize
- attr: use this to add any attributes
- eg. attr: 'data-something="something something"'
Todo:
- convert png, jpg, webp
- bg colour support for letterbox
#}
{% if img %}
<img
loading="lazy"
{% if id %} id="{{ id }}" {% endif %}
{% if class %} class="{{ class }}" {% endif %}
alt="{{ alt ? alt : img.title }}"
{{ attr }}
{% if w %}
width="{{ w }}"
{% if not h %}
{% set h = (w / img.width * img.height)|round %}
{% endif %}
height="{{ h }}"
{% if letterbox %}
src="{{ img.src|letterbox(w,h) }}"
srcset="{{ img.src|letterbox(w,h) }} 1x, {{ img.src|letterbox(w*2,h*2) }} 2x"
{% else %}
src="{{ img.src|resize(w,h) }}"
srcset="{{ img.src|resize(w,h) }} 1x, {{ img.src|resize(w*2,h*2) }} 2x"
{% endif %}
{% else %}
{# no width? use raw w, h #}
width="{{ img.width }}"
height="{{ img.height }}"
src="{{ img.src }}"
srcset="{{ img.src|retina(1) }} 1x, {{ img.src|retina(2) }} 2x"
{% endif %}
{# Close the tag and we are done! #}
>
{% else %}
<pre>!Need img parameter!</pre>
{% endif %}
{% endspaceless %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment