Adding figures with captions to images in markdown with eleventy
Problem
Markdown is really flexible for writing text, but it's support for images is quite simplistic.
Standard images in markdown
![A kitten](http://placekitten.com/400/300)
outputs:
<img src="http://placekitten.com/400/300" alt="A kitten">
e.g.
However I want to generate something more useful to readers, i.e. images with nice captions like:
<figure>
<img src="http://placekitten.com/400/300" alt="A kitten">
<figcaption>Chesney the Kitten attempts a giant leap<figcaption>
<figure>
Now you can do this by just including HTML in your markdown, but this gets boring fast, and I wanted a single markdown tag to do this with.
Solution
Use the markdown-it
plugin markdown-it-image-figures
.
Full plugin docs are here, but if you want to output simple images with alt tags and title like:
<figure>
<img src="fig.png" alt="This is an alt">
<figcaption>This is a caption</figcaption>
</figure>
you need the following config alongside your markdown library configuration in your .eleventy.js
file:
let markdownIt = require("markdown-it");
let options = {
// whatever options you have set for the library here
};
let mdfigcaption = require('markdown-it-image-figures');
let figoptions = {
figcaption: true
};
const mdLib = markdownIt(options).use(mdfigcaption, figoptions);
module.exports = function (config) {
//other config here
config.setLibrary("md", mdLib);
}
N.B. the figcaption
option sets the plugin to use a specified image title as the fig caption.
Usage
![A Kitten](http://placekitten.com/400/300 "Chesney the Kitten attempts a giant leap")
outputs the following HTML
<figure>
<img src="http://placekitten.com/400/300" alt="A kitten">
<figcaption>Chesney the Kitten attempts a giant leap<figcaption>
<figure>
which renders with a bit of styling like:
Gotchas to watch out for
- you have to pass the figcaption options in with the plugin, not in with the main libary options.
- leave a blank line above the markdown image tag otherwise it doesn't seem to render properly.
- You’re only allowed one module.exports in your configuration file, so make sure you only add the config to you tour existing one!