Creating a photo album using 11ty

This blog is created using the wonderful static site generator 11ty. I wanted to add a single page which would show a gallery of all the photos posted in all of the posts on the site.

The below few snippets show how I managed to accomplish that with a few lines of Javascript.

Firstly, we need to add a custom collection which would list every post that has the tag "photography":

eleventyConfig.addCollection("gallery", (collection) => {
return collection
.getFilteredByTag("photography")
.sort((p1, p2) => p1.date - p2.date);
});

Then, on photos.njk we will iterate over the collection and using a custom filter (shown underneath), we will output each individual image:

<div>
{% for post in collections.gallery | reverse %}
{% for image in post.content | markdownToImagesOnly %}
{{ image | safe }}
{% endfor %}
{% endfor %}
</div>

And finally, the actual meat of the solution which is a custom filter that renders the Markdown to HTML and then extracts all the <img> tags:

    eleventyConfig.addFilter("markdownToImagesOnly", str => {
const markdownLibrary = markdownIt({html: true});
const inline = markdownLibrary.renderInline(str).replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');
return inline.match(/<img\s+[^>]*?>/g);
});

And with that, the solution is complete. You can see the results on jeeb.uk/photos.