Search code examples
jekyllliquid

How to use boolean negation in "where:"?


I am trying to write a query to retrieve posts of all categories but the category "Personal".

I have the following code to retrieve all posts which are tagged as "Personal", so I tried to use " ! " and " not " to get which are not "Personal".

{% assign sorted-posts = site.posts | where: "categories", "Personal" %}
  ...
{% endfor %}

So, I tried this:

{% assign sorted-posts = site.posts | not where: "categories", "Personal" %}
  ...
{% endfor %}

and

{% assign sorted-posts = site.posts | ! where: "categories", "Personal" %}
  ...
{% endfor %}

It didn't work. How can I use " not " or " ! " in Liquid?


Solution

  • As post.categories is an array, you can check if it contains a certain value with contains filter. eg : if post.categories contains "Personal"

    The unless control flow tag, which is equivalent to "if not" can now be used to print all posts that are not from "personal" category.

    <ul>
    {% for post in site.posts %}
      {% unless post.categories contains "Personal" %}
        <li><a href="{{ site.baseurl }}{{ post.url }}">{{ post.title }}</a></li>
      {% endunless %}
    {% endfor %}
    </ul>