1
votes

I'm using Jekyll to construct a site and am trying to create a 'Recent Posts' array at the end of every post using Liquid logic.

I want this array to consist of all posts except the post of the page you're currently on.

So, I started with:

{% for post in site.posts limit:2 %}
  {% if post.title != page.title %}
    //render the post
  {% endif %}
{% endfor %}

This works, except that my limit: 2 is causing issue. Since Liquid limits before the if logic, if it indeed encounters the post whose title equals the current page's title, it will (correctly) not render it, but it will consider the limit "satisfied" - and I end up with only 1 related post instead of 2.

Next I tried creating my own array of posts:

{% assign currentPostTitle = "{{ page.title }}" %}
{% assign allPostsButThisOne = (site.posts | where: "title" != currentPostTitle) %}

{% for post in allPostsButThisOne limit:2 %}
  //render the post          
{% endfor %}

This doesn't work because I can't get the where filter to accept the != logic.

How can I successfully get around this issue?

2

2 Answers

4
votes

You can use a counter :

{% assign maxCount = 2 %}
{% assign count = 0 %}
<ul>
{% for post in site.posts %}
  {% if post.title != page.title and count < maxCount %}
    {% assign count = count | plus: 1 %}
    <li>{{ post.title }}</li>
  {% endif %}
{% endfor %}
</ul>
0
votes

As you have mentioned, you only miss on this code:

{% assign allPostsButThisOne = (site.posts | where: "title" != currentPostTitle) %}

You my try to use contains with unless

{% assign allPostsButThisOne = (site.posts | where_exp:"post", "unless post.title contains currentPostTitle") %}