add related posts and update some styling

This commit is contained in:
2026-02-20 08:36:46 -08:00
parent c4b549bc75
commit 7d1fe776c7
7 changed files with 73 additions and 19 deletions

View File

@ -8,7 +8,7 @@ tags:
- software
---
recently I wrote *several* sites using [Eleventy](https://www.11ty.dev/){target="_blank" rel="external"} (4? 5?). Including, over the past few days, this one! That's right, if you're reading this, we're now running on 11ty and hosted by [heckin.technology](https://heckin.technology/){target="_blank" rel="external"}. See ya, GitHub. Won't miss ya.
recently I wrote *several* sites using [Eleventy](https://www.11ty.dev/){target="_blank" rel="external"} (4? 5?). Including, over the past few days, rewriting this one! That's right, if you're reading this, we're now running on 11ty and hosted by [heckin.technology](https://heckin.technology/){target="_blank" rel="external"}. See ya, GitHub. Won't miss ya.
I've compiled some of the things I've learned in a standalone site: [11ty Lessons](https://inherentlee.codeberg.page/lessons/){target="_blank" rel="external"}.
@ -26,18 +26,19 @@ while that is useful for *this* site, when building another site I wanted to see
I started by referring to [this GitHub issue about related posts](https://github.com/11ty/eleventy/discussions/2534){target="_blank rel="external"}. I had to fix a few errors that arose from the suggested code.
I also wanted to make two changes:
I also wanted to make three changes:
1. I didn't want to just see posts that shared *all* tags, but rather posts that shared *any* tag
1. I wanted to randomly add a few posts instead of just getting whatever was first (with a shared tag) in the post order
1. I wanted to exclude the posts that I could reach with between-post pagination
### filters.js
after adjusting for those needs, I had the following in `filters.js`:
```js
eleventyConfig.addNunjucksFilter("excludeFromCollection", function (collection=[], pageUrl=this.ctx.page.url) {
return collection.filter(post => post.url !== pageUrl);
eleventyConfig.addFilter("excludeFromCollection", function (collection=[], urls=[this.ctx.page.url]) {
return collection.filter(post => urls.indexOf(post.url) === -1);
});
eleventyConfig.addFilter("filterByTags", function(collection=[], ...requiredTags) {
@ -67,7 +68,12 @@ I used this in my post layout. `filterTagList` comes with the base blog by defau
{% raw %}
```html
{% set relevantTags = tags | filterTagList %}
{% set postlist = collections.posts | filterByTags(relevantTags) | excludeFromCollection(page.url) | randomize | head(2) %}
{% set olderPost = collections.posts | getPreviousCollectionItem %}
{% set newerPost = collections.posts | getNextCollectionItem %}
{% set urlsToExclude = [page.url, olderPost.url, newerPost.url]}
{% set postlist = collections.posts | filterByTags(relevantTags) | excludeFromCollection(urlsToExclude) | randomize | head(3) %}
{% if postlist.length %}
<section class="related-posts">
<h2>related posts</h2>