Use FrontMatter to to pull in a related posts collection in eleventy?

Viewed 276

Essentially, I want to show related posts on a post page. So this is the FrontMatter.

---
title: Cape Fear
date: 2020-05-28
image: capefear
tags: movie
---

Can I then grab a collection on that post based on what the tag is?

<ul class="related">
  {%- for page in collections.{{tag}} -%}
    <li><a href="{{ page.url }}">{{ page.data.title }}</a></li>
  {%- endfor -%}
  </ul>

This doesn't work. Any ideas on how to output the tag in the collections loop?

1 Answers

I think page in site.tags[tag_name] would be the proper way of doing it.

So if you want to have a list of related posts on your page based on the tags, that could be one of the ways of doing it:

{% assign related_posts = [] %}
{%- for related_tag in page.tags | split: '|' %}
  {% assign related_posts = related_posts | concat: site.tags[related_tag] | uniq %}
{%- endfor %}

<ul class="related">
  {%- for related_post in related_posts %}
    <li><a href="{{ related_post.url }}">{{ related_post.title }}</a></li>
  {%- endfor %}
</ul>

Here I first create a list of all posts having the common tags with the current page, than I list them through.

Related