Ognjen Regoje bio photo

MY NAME IS
Ognjen Regoje
BUT YOU CAN CALL ME OGGY


I make things that run on the web (mostly).
More /ABOUT me.

me@ognjen.io Twitter LinkedIn Instagram Github

Flatten Plugin for Jekyll

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.

#jekyll #liquid #technical