Liquid filter collection where not null

Viewed 2182

In my front matter for some pages (not all) I have:

---
top-navigation:
    order: 2
---

Using liquid I want to filter all site pages which have a top-navigation object and sort by top-navigation.order.

I'm trying sort:'top-navigation.order' but that's throwing an exception of undefined method [] for nil:NilClass. I tried where:"top-navigation", true but it's not equating truthy values.

How can I filter for pages that have top-navigation and then sort?

2 Answers

In Jekyll 3.2.0+ (and Github Pages) you can use the where_exp filter like so:

{% assign posts_with_nav = site.posts | where_exp: "post", "post.top-navigation" %}

Here, for each item in site.posts, we bind it to the 'post' variable and then evaluate the expression 'post.top-navigation'. If it evaluates truthy, then it will be selected.

Then, putting it together with the sorting, you'd have this:

{%
  assign sorted_posts_with_nav = site.posts 
  | where_exp: "post", "post.top-navigation" 
  | sort: "top-navigation.order"
%}

Liquid also has the where filter which, when you don't give it a target value, selects all elements with a truthy value for that property:

{% assign posts_with_nav = site.posts | where: "top-navigation" %}

Unfortunately, this variant does not work with Jekyll.

Related