Search code examples
arraysjekylllimitblogsliquid

Jekyll truncate number of blog posts conditional on excluding some


On my Jekyll website, I have an overview page on which I list my last 10 blog posts.

However, I also assign a tag exclude to some of my blog posts and those I don't want to show. This works, but then I don't get the last 10 blog posts, but 10 minus the number of exclude blog posts.

Here is how that looks like:

---
layout: page
title: "Last posts"
permalink: /last/
---

### Last posts

{% for post in site.posts limit:10 %}
    {% unless post.category == "exclude"%}
      * {{ post.date | date_to_string }} » [ {{ post.title }} ]({{ post.url }})
    {% endunless %}
{% endfor %}

How can I always show the last 10 non-exclude blog posts?


Solution

  • To show the last 10 non-exclude blog posts:

    1. Create an array with posts that doesn't contain the exclude tag.

      {% assign nonexcludeposts = ''|split:''%}
      {% for post in site.posts %}
          {% unless post.category == "exclude"%}
          {% assign nonexcludeposts = nonexcludeposts|push:post%}
          {% endunless %}
      {% endfor %}
      
    2. Display 10 most recent posts

      <ul>
      {% for post in nonexcludeposts limit:10 %}
            <li>
            <a href="{{post.url|absolute_url}}">{{post.title}}</a>
            </li>
      {% endfor %}
      </ul>