Split Collections in Jekyll

Jan 22, 2020

One thing I love most about Jekyll is its extensibility. I can customize it however I want. It feels like the perfect balance between it just working out of the box while sitll allowing the ability to make it fit your needs.

Today, this was my need:

Here it is. Put it in your _plugins directory:

module DataGenerator
  class Generator < Jekyll::Generator
    safe true

    def generate(site)
      split_posts!(site)

      site
    end

    def split_posts!(site)
      site.collections["writing"] = Jekyll::Collection.new(site, "Writing")
      site.collections["notes"] = Jekyll::Collection.new(site, "Notes")

      site.posts.docs.each do |doc|
        if doc.data.fetch("tags")&.include? "note"
          site.collections["notes"].docs << doc
        else
          site.collections["writing"].docs << doc
        end
      end

      site.collections["writing"] = sort(site.collections["writing"], "date")
      site.collections["notes"] = sort(site.collections["notes"], "date")

      site
    end

    def sort(collection, key)
      collection.docs = collection.docs.sort_by {|doc| doc.data[key] }.reverse
      collection
    end
  end
end

I had to do a bit of reading to figure out how the Collections API worked, but once I had that figured out, the rest was easy.