Skip to content

Instantly share code, notes, and snippets.

@OleVik
Created May 14, 2016 12:48
Show Gist options
  • Save OleVik/a7604215f127763b71bd8b8788d45cfd to your computer and use it in GitHub Desktop.
Save OleVik/a7604215f127763b71bd8b8788d45cfd to your computer and use it in GitHub Desktop.
Quick Twig macro for generating srcset-attribute for images
{% macro img(file, base, caption="", sizes="100vw") %}
{% set filename = file|split('.') %}
{% set filenameext = "." ~ filename|last %}
{% set file = file|replace({(filenameext): ""}) %}
<img
src="{{ base }}/{{ file }}-320{{ filenameext }}"
srcset="{{ base }}/{{ file }}-320{{ filenameext }} 320w,
{{ base }}/{{ file }}-480{{ filenameext }} 480w,
{{ base }}/{{ file }}-640{{ filenameext }} 640w,
{{ base }}/{{ file }}-960{{ filenameext }} 960w,
{{ base }}/{{ file }}-1280{{ filenameext }} 1280w,
{{ base }}/{{ file }}-1600{{ filenameext }} 1600w,
{{ base }}/{{ file }}-1920{{ filenameext }} 1920w,
{{ base }}/{{ file }}-2240{{ filenameext }} 2240w"
sizes="{{ sizes }}"
alt="{{ caption }}"
/>
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment