Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter site.related_posts in Jekyll

Tags:

ruby

jekyll

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:

  1. Foo (Categories: A, B)
  2. Bar (Categories: A, C, D)
  3. 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.)

like image 481
Nikos Baxevanis Avatar asked Jun 05 '12 23:06

Nikos Baxevanis


2 Answers

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 %}
like image 134
kale Avatar answered Sep 24 '22 02:09

kale


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 %}
like image 31
gutierrezalex Avatar answered Sep 23 '22 02:09

gutierrezalex