List all Posts That are in the Same Category of a Given Post

I have a set of files in _posts/ folder that shares the same category, and use the same layout.
Take the following two posts as an example:

_posts/2021-10-22-post-one.html:

---
title: "Post One"
permalink: /posts/one.html
categories: aboutstuff
layout: post
---
[...]

_posts/2021-10-22-post-two.html:

---
title: "Post Two"
permalink: /posts/two.html
categories: aboutstuff
layout: post
---
[...]

When building each of the posts above, I want Jekyll to generate a list of the other posts under the same category. The snippet below illustrates what the code I expected to work:

_layouts/post.html:

{{ content }}
{% for item in site.categories[page.categories] %}
  <a href="{{ item.url }}" target="_self" draggable="false">
    {{ item.title }}
  </a>
{% endfor %}

After executing Jekyll, the following resulting files are expected:
/posts/one.html:

[...]
<a href="/posts/two.html" target="_self" draggable="false">
  Post Two
</a>

<a href="/posts/one.html" target="_self" draggable="false">
  Post One
</a>

/posts/two.html:

[...]
<a href="/posts/two.html" target="_self" draggable="false">
  Post Two
</a>

<a href="/posts/one.html" target="_self" draggable="false">
  Post One
</a>

Unfortunately, the files generated do not contain the links that they should have.

Something I noticed is that by placing the category value directly between the square brackets ( like in {% for item in site.categories[“aboutStuff”] %} )`does list all posts with the value aboutStuff set to its category property.

What am I missing? Why is the code in post.html not creating the appropriate links?


Environment:
Jekyll Version: 4.2.1
Operating System: Windows 10

try page.category in the for loop. That probably isn’t it but could be.

So your example for posts/one.html EXPECTED are just that - expected but you don’t get it? what do you get? anything? sometimes you can look at the html created and see if created blank a tags or something to help suss it out.

you may also want to try just outputting the page.categories by itself and see if you can get that, then work on the loop as maybe in the loop you need to format it differently? then you would know which is the problem - the loop or the variable.

1 Like

ahhh:

page.categories is correct but jekyll needs it to be a string but it is not. Try assigning or capturing it like the link above does.

1 Like