Search code examples
jekyllliquid

Jekyll `where_exp` filter with "contains" expression


I'm creating a page for authors for my Jekyll website. On this page, I want to show all the posts that this particular author has written.

This is how my posts look like:

title: "Some title"
authors: [author1, author2]

For keeping the list of authors, I use collections.

An author looks like that:

short: author1
name: "Author 1 Full Name"

Now for author1 I want to find all the articles of this author. I'm trying to use where_exp for that:

{% assign articles = site.posts | where_exp: "authors", "authors contains page.short" %}

In this case, page.short contains author1.

But the list articles is empty. Do you know what could be the problem?


Solution

  • You have a syntax issue in your filter, you can refer to the way it is used in the documentation.

    You can see there that it is used as

    {{ site.members | where_exp:"item", "item.projects contains 'foo'" }}
    

    But in your attempt, you are missing to define what field of the item should the contains query.

    In the code

    where_exp:"item", "item.projects contains 'foo'"
    

    we do define an item out of an array, and then we expect this item to have a field projects; where we want only the one containing the project foo

    When in your code

    where_exp: "authors", "authors contains page.short" 
    

    You are saying that the item is actually called authors and you want the item itself to contain page.short

    A more correct approach would be:

    site.posts | where_exp: "post", "post.authors contains page.short"
    

    Because the items of your array site.posts are actually posts, so an item of it is a post.
    Then, on a post, you expect a field authors, so post.authors to contain a specific string.