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
.)
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 %}
Make sure each post has a category in the YAML front matter, then add this to where you would like to show the post relating CATEGORY_NAME:
{% for post in site.categories.CATEGORY_NAME %}
<li>
<a href="{{ post.url }}">
<img src="{{ post.thumbnail }}">
<p>{{ post.excerpt }}</p>
</a>
</li>
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With