Filter site.related_posts in Jekyll
jekyll, ruby
Solution
I don't have the ability to test this right now, but something like this will work given Liquid's limited syntax:
{% for post in site.related_posts limit:5 %}
{% assign match = false %}
{% for category in post.categories %}
{% if page.categories contains category %}
{% assign match = true %}
{% endif %}
{% endfor %}
{% if match %}
<li><a href="{{ post.url }}">{{ post.title }}</a></li>
{% endif %}
{% endfor %}
Problem
I am very new to Jekyll and Ruby (yet, very excited). Without using a plugin, I am trying to find a way to filter the `site.related_posts`. For example, I am reading the post with title `Foo` and categories `A, B`. The site contains in total 3 posts: - `Foo` (Categories: A, B) - `Bar` (Categories: A, C, D) - `Zoo` (Categories: B, F) By the default, in Jekyll we do this: {% for post in site.related_posts limit:5 %} {% endfor %} However, the above code returns all the (3) posts. A post contains many categories, so categories should be an array. How can I modify the code and return only those whose categories intersect with the current post's categories? (In this example, I would like the code to return only `Foo` and `Zoo`.)