Skip to content

Instantly share code, notes, and snippets.

@geoffyuen
Last active May 12, 2020 12:36
Show Gist options
  • Save geoffyuen/c6e1e362073110582aebbd9090b76156 to your computer and use it in GitHub Desktop.
Save geoffyuen/c6e1e362073110582aebbd9090b76156 to your computer and use it in GitHub Desktop.
Webp with fallback for Timber/Twig
{% spaceless %}
{#
This Timber twig will output an <picture> with fallbacks, srcset x2, alt, width and height
Usage:
`{% include '_webp.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:
- bg colour support for letterbox
https://github.com/scottjehl/picturefill/issues/278
#}
{% if img %}
<picture
{% if id %} id="{{ id }}" {% endif %}
{% if class %} class="{{ class }}" {% endif %}
{{ attr }}
>
{# source for webp #}
<source type="image/webp"
{% if w %}
{% if not h %}
{% set h = (w / img.width * img.height)|round %}
{% endif %}
{% if letterbox %}
srcset="{{ img.src|letterbox(w,h)|towebp }} 1x, {{ img.src|letterbox(w*2,h*2)|towebp }} 2x"
{% else %}
srcset="{{ img.src|resize(w,h)|towebp }} 1x, {{ img.src|resize(w*2,h*2)|towebp }} 2x"
{% endif %}
{% else %}
{# no width? use raw w, h #}
srcset="{{ img.src|towebp }}"
{% endif %}
>
{# /source (webp) #}
{# source for original fmt #}
<source
{% if w %}
{% if letterbox %}
srcset="{{ img.src|letterbox(w,h) }} 1x, {{ img.src|letterbox(w*2,h*2) }} 2x"
{% else %}
srcset="{{ img.src|resize(w,h) }} 1x, {{ img.src|resize(w*2,h*2) }} 2x"
{% endif %}
{% else %}
{# no width? use raw #}
srcset="{{ img.src }}"
{% endif %}
>
{# /source (original fmt) #}
<img
loading="lazy"
class="ma0 db"
alt="{{ alt ? alt : img.title }}"
{% if w %}
width="{{ w }}"
height="{{ h }}"
{% if letterbox %}
src="{{ img.src|letterbox(w,h) }}"
{% else %}
src="{{ img.src|resize(w,h) }}"
{% endif %}
{% else %}
{# no width? use raw w, h #}
width="{{ img.width }}"
height="{{ img.height }}"
src="{{ img.src }}"
{% endif %}
{# Close the tag and we are done! #}
>
</picture>
{% 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