The general idea is to take the built-in collection.all
, filter it down by the fileSlugs provided through the front matter and sort the filtered collection by their position in related
:
Create a custom filter in .eleventy.js
:
eleventyConfig.addFilter('filterRelated', (collection = [], related = []) => {
const filtered = collection.filter(page => related.includes(page.fileSlug));
return filtered.sort( (a, b) => related.indexOf(a.fileSlug) - related.indexOf(b.fileSlug));
});
Update your front matter in my-awesome-post.md
to look like this:
---
title: My Awesome Post
related:
- another-awesome-post
- 11ty-review
---
Add a related articles section to your template (article.njk
in my case):
{% if related %}
<section class="related-articles">
{%- for article in collections.all | filterRelated(related) -%}
<a class="card" href="/{{ article.data.page.fileSlug }}" title="{{ article.data.title }}">
{% if article.data.image %}
<img src="/img/{{ article.data.image }}" alt="" />
{% else %}
<div class="placeholder"></div>
{% endif %}
<div class="card-content">
<p class="category">{{ article.data.category }}</p>
<h4>{{ article.data.title }}</h4>
<p>{{ article.data.description }}</p>
</div>
</a>
{%- endfor -%}
{% endif %}