Skip to content

Instantly share code, notes, and snippets.

@slightlyoff
Created August 20, 2020 20:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slightlyoff/f38cb53eb8af1535149865d31dae569a to your computer and use it in GitHub Desktop.
Save slightlyoff/f38cb53eb8af1535149865d31dae569a to your computer and use it in GitHub Desktop.
image/picture/figure sizing shortcode
// Here's how I use this shortcode in my .md files:
//
// {% picture
// "/2020/06/platform-adjacency-theory/relevance_gap_opt.png",
// "Mind the gap."
// %}
//
// And for the <figure> version that puts the alt text visibly below the image:
//
// {% figure
// "/assets/images/IMG_20200225_154710_1_MP.jpg",
// "Simpler times, Tokyo." %}
//
// From my .eleventy.js; should do something more reusable fo sho.
// An iteration on Phil Hawksworth's Netlify LMS <picture> img generator
let getPicture = (url, alt="Missing alt text", width, height, style) => {
let w = width ? width : "500";
let w_attr = width ? `width="${width}"` : "";
let h_attr = height ? `height="${height}"` : "";
let s_attr = style ? `style="${style}"` : "";
return `<picture>
<source
media="(min-width: 1200px)"
srcset="${url}?nf_resize=fit&w=800 1x,
${url}?nf_resize=fit&w=1200 1.5x,
${url}?nf_resize=fit&w=1600 2x,
${url}?nf_resize=fit&w=2400 3x" >
<source
media="(min-width: 740px)"
srcset="${url}?nf_resize=fit&w=700 1x,
${url}?nf_resize=fit&w=1150 1.5x,
${url}?nf_resize=fit&w=1400 2x,
${url}?nf_resize=fit&w=2100 3x" >
<source
media="(min-width: 350px)"
srcset="${url}?nf_resize=fit&w=400 1x,
${url}?nf_resize=fit&w=600 1.5x,
${url}?nf_resize=fit&w=800 2x,
${url}?nf_resize=fit&w=1200 3x" >
<source
media="(min-width: 300px)"
srcset="${url}?nf_resize=fit&w=300 1x,
${url}?nf_resize=fit&w=450 1.5x,
${url}?nf_resize=fit&w=600 2x,
${url}?nf_resize=fit&w=900 3x" >
<img src="${url}?nf_resize=fit&w=400"
alt="${alt}" ${w_attr} ${h_attr} ${s_attr}
loading="lazy">
</picture>`;
};
config.addShortcode("picture", getPicture);
config.addShortcode("figure", (url, alt, ...otherargs) => {
let pictureMarkup = getPicture(url, alt, ...otherargs);
return `
<figure>
${pictureMarkup}
<figcaption>${alt}</figcaption>
</figure>
`;
});
config.addShortcode("figurelink", (imgurl, linkurl, alt, ...otherargs) => {
let pictureMarkup = getPicture(imgurl, alt, ...otherargs);
return `
<figure>
<a href="${linkurl}" alt="${alt}">
${pictureMarkup}
</a>
<figcaption>${alt}</figcaption>
</figure>
`;
});
// Use a single glob as it's much faster than many
let exts = [ "css", "js", "jpg",
"gif", "png", "svg", "webp", "avif",
"webm", "av1", "mp3", "ogg", "mp4" ];
config.addPassthroughCopy(`_posts/**/*.(${exts.join("|")})`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment