Search code examples
jekyllliquidmarkup

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


Solution

  • 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