Ognjen Regoje bio photo

Ognjen Regoje
But you can call me Oggy


I make things that run on the web (mostly).
More ABOUT me and my PROJECTS.

me@ognjen.io LinkedIn

Flatten Plugin for Jekyll

#jekyll #liquid #technical

I wanted to be able to get a list of categories from a group of posts. That’s easy enough to do using the map liquid filter:

{{posts | map: 'categories'}}

The result is an array of arrays.

There are two downsides to this: I’d have to use a nested loop to list them, and I’d have to manually track duplicates.

Instead, a better approach is to map the categories and then flatten the array.

Unfortunately, liquid doesn’t have a flatten filter but fortunately it’s simple to add a new filter.

# _plugins/flatten.rb

module Jekyll
  module Flattener
    module FlattenerFilter
      def flatten(input)
        return input.flatten
      end
    end
  end
end

Liquid::Template.register_filter(Jekyll::Flattener::FlattenerFilter)

With this what I can do is:

{{posts | map: 'categories' | flatten | uniq}}

And then looping through the cats is very simple.