Skip to content

Instantly share code, notes, and snippets.

@jackarmley
Last active September 5, 2015 12:37
Show Gist options
  • Save jackarmley/d5a8f76ea85ff7381111 to your computer and use it in GitHub Desktop.
Save jackarmley/d5a8f76ea85ff7381111 to your computer and use it in GitHub Desktop.
Jade image mixin
//-
//- Srcset mixin
//- @requires site.data.images
//- https://ericportis.com/posts/2014/srcset-sizes/
//-
mixin image(src,alt)
//- 1:
//- Set initial vars
//- Set counters
-var i = 0;
-var len = 0;
//- Set empty vars for
//- image default src, sizes and srcset
-var defaultsrc = '';
-var srcset = '';
-var sizes = '';
//- Grab values from mixin args
-var alt = alt || false;
-var imgname = src.split('.')[0]
-var ext = '.' + src.split('.')[1]
//- Get the length of the images object
each val, index in site.data.images
-len++;
//- 2:
//- Loop through images
//- and get attributes
each val, index in site.data.images
//- Create srcset and sizes strings
-srcset = srcset + imgname + '-' + index + ext + ' ' + val.width + 'w';
-sizes = sizes + val.sizes;
//- Use the first provided size
//- as the default image
if i === 0
-defaultsrc = imgname + '-' + index + ext;
//- Comma sep srcset and sizes strings
if i < (len - 1)
-srcset = srcset + ',';
-sizes = sizes + ',';
//- Add a default size to the end
//- of the sizes string
if i === (len - 1)
-sizes = sizes + ', 100vw'
//- Add to the i counter
-i++;
//- 3.
//- Set markup
img(src=defaultsrc srcset=srcset sizes=sizes alt=alt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment