lastnoob
lastnoob

Reputation: 648

Exclude current post from recent posts query in Jekyll?

So heres a recent posts query with the last 5 posts.

 {% for post in site.posts limit:5 %}
     <li>
    < a href="{{ post.url }}">{{ post.title }}</a>
     </li>
   {% endfor %}

However, this shows the current one too, if its one of the 5 latest posts. I tried to include an if statement which check for the URL, but how can I add +1 to the limit variable?

P.S.: I included a space in the anchor tag so its readable as code

Upvotes: 4

Views: 1507

Answers (2)

Kais
Kais

Reputation: 81

A better option is to use:

{% assign posts = site.posts | where_exp:"post","post.url != page.url" %}
{% for post in posts limit:5 %}
  <li>
    <a href="{{ post.url }}">{{ post.title }}</a>
  </li>
{% endfor %}

What it does:

  • Create a new variable called posts.
  • Use the where_exp filter to filter out the post that has the same URL as the current page.
  • Loop over this new variable with a limit of 5 (a maximum of 5 posts).

Upvotes: 8

Mr. Hugo
Mr. Hugo

Reputation: 12592

Checking the url should work. Just loop over six items and hide the last one when you do not find a match.

{% for post in site.posts limit:6 %}
  {% if post.url != page.url %} 
    {% if forloop.index < 6 or found %}
      <li>
        <a href="{{ post.url }}">{{ post.title }}</a>
      </li>
    {% endif %}
  {% else %}
    {% assign found = true %} 
  {% endif %}
{% endfor %}

What the code does (step by step):

  • loop over 6 posts
  • check if the post is NOT the current page/post
  • if you are on loop/iteration 1 to 5 OR you have found the current item*
  • then show the post you loop/iterate over

*allowing you to loop/iterate over post number 6

Upvotes: 7

Related Questions