A template to optimizing images based on markdown tags!
This is a demo of how you can run 11ty's image plugin across any part of your site, no shortcodes required!
The goal:
img
tags in a given templatepicture
elementNote: this only works in 11ty's latest v1.0 beta. You can install this by adding the @beta
flag to your 11ty install: npm i @11ty/eleventy@beta
npm i
npm run dev
to spin up the dev servernpm run build
for production buildsThis code snippet (found in the .eleventy.js
config) powers everything you're seeing:
module.exports = function (eleventyConfig) {
eleventyConfig.addPassthroughCopy('img')
eleventyConfig.addExtension('md', {
read: true,
compile(markdown) {
return async function render(data) {
// let 11ty process markdown how it normally would
const html = await this.defaultRenderer(markdown);
const $ = cheerio.load(html);
// if this markdown file has the "blog" tag applied...
if (data.tags?.includes('blog')) {
await Promise.all([
// loop over all the images in the document
$('img').toArray().map(async (img) => {
// grab the image attributes
const { src = '', alt = '', sizes = '100vw' } = img.attribs;
// convert to an optimized image
const optimizedImage = await imageShortcode(src, alt, sizes);
// and replace the image with an optimized one
$(img).replaceWith(optimizedImage);
})
])
}
return $.html();
}
}
})
}