Skip to content

Instantly share code, notes, and snippets.

@nhoizey
Last active October 8, 2024 12:58
Show Gist options
  • Save nhoizey/a86ef10ceb86dc31c31145777bcaeef2 to your computer and use it in GitHub Desktop.
Save nhoizey/a86ef10ceb86dc31c31145777bcaeef2 to your computer and use it in GitHub Desktop.
Transform a `title` attribute into `figure`/`ficaption` tags

This is how I create images with caption in my Markdown content used in Eleventy.

This image:

![This is the alt text](path/to/the/image.jpg "This is the **title**")

Becomes this HTML:

<figure>
  <img src="path/to/the/image.jpg" alt="This is the alt text">
  <figcaption>This is the <strong>title</strong></figcaption>
</figure>

I use it as a hook after transforming simple images into responsive images with srcset/sizes attributes thanks to https://nhoizey.github.io/eleventy-plugin-images-responsiver/

const runAfterHook = (image, document, documentUrl) => {
let caption = undefined;
// Extract `title` attribute of the image
const title = image.getAttribute('title');
// If there's a title value,
// parse it for Markdown content
if (title !== null) {
caption = md.render(title.trim());
}
// If there's a caption,
// add a `<figure>` around the image,
// with the caption in a `<figcaption>`
if (caption) {
let figure = document.createElement('figure');
figure.classList.add(...image.classList);
image.classList.remove(...image.classList);
let figCaption = document.createElement('figcaption');
figCaption.innerHTML = caption;
figure.appendChild(image.cloneNode(true));
figure.appendChild(figCaption);
image.replaceWith(figure);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment