Compact Plugin for Jekyll (where not nil)
I wanted to generate an index of metadata from posts in Jekyll. The field that I wanted to index wasn’t compulsory, it was an additional one that I sometimes set, and sometimes didn’t.
That’s trivial to do by mapping it:
{{posts | map: 'new_field' | uniq}}
However, that always produced one nil
in the results.
That can easily be handled by adding an if
but I didn’t want to have to add it every time I wanted to generate this index.
Instead, I wanted it to not appear in the first place.
Unfortunately, liquid does not have a where not
filter, only a where
. Fortunately, it’s simple to add a filter in Jekyll:
# _plugins/compact.rb
module Jekyll
module Compacter
module CompacterFilter
def compact(input)
return input.compact
end
end
end
end
Liquid::Template.register_filter(Jekyll::Compacter::CompacterFilter)
With this what I can do is:
{{posts | map: 'new_fields' | uniq | compact}}
And the result wont have any nils. Much cleaner then having to if
every time.