Jekyll Collections are amazing. They allow you to create different types of content beyond the traditional blog post. You can create collections of people, items on a todo list, anything. This feature was the tipping point that made me use Jekyll for this site over a dynamic database driven CMS like Drupal. This article will show you how to use collections by example, from the basics to advanced techniques.
The Basics
I use collections all over this site. In the Voices in Colour section each voice is an item in a ‘voices’ collection. Each item is a YAML file with keys and values:
This file can be called anything and is put in the collections folder, in my case called _voices
.
You then print out the items in the collection with:
In _config.yml
the final configuration that glues it all together is:
This tells Jekyll to look in the _voices
folder and exposes the collections as the site.voices
variable.
Pretty nifty yeah? You can make almost anything with these simple building blocks.
Advanced
Filters
You can filter collections by a key in the YAML file. Here my key is type
and my value is blue
.
Then loop through the resulting filtered array like you would any other.
Nested Data
A collection can have nested keys and values. The structure is like this:
Here each voice has many “modes”. By using dashes we can store multiple items inside a key. Each item has a key and a value. You output the values with the usual for loop on the desired page:
File structure
Collections by default are placed in the root of your Jekyll site. I have 6 collections on this site and the top level folder can start to get messy. If you want to put your collections in a collections
folder then add this to your _config.yml
:
You will need to put your _posts
directory inside this folder too or Jekyll will complain.
Done
Well there you have it! Collections are a great way to manage different types of content on your site. Who needs a CMS?