Sort and filter in jekyll

We are right on the heels of the next release of Jekyll and I just updated Level Up Lunch to build with 2.0.0.alpha.2. I definitely consider myself a ruby rookie and it showed while trying to install the pre release. Luckily the jekyll community was open and with their help we were able to get past my hiccup. Two features added in this release that I have been anxiously waiting for was support to sort jekyll pages and filtering elements in an array.

Sort pages by title

By default, jekyll orders files based on folder structure and file name. In Level Up Lunch's java examples, we name markdown files the same as the java files used to allow us to easily link over to github and break up the folders for organization. This presents a couple of problems. First, not all page titles are the same as the file name. Secondly, we have files that exists across subfolders that apply to the same category.

Now without having to create a plugin you can easily apply a sort. Below is the snippet we used to sort pages by title while generating the java examples index page.

{% assign sorted_pages = (site.pages | sort: 'title') %}
{% for page in sorted_pages %}
    <li class="cardmenu-item"><a href="{{ page.url }}">{{ page.title }}</a></li>
{% endfor %}

Filter array by layout

At this point we have 4 major layouts, java exercises, java tutorials, java examples and blog posts. The first three categories are all grouped together under pages. When we render a specific index page we have a need to show pages by a specific layout or filter pages by layout. The snippet shows before and after on how we approached filtering pages by layout.

BeforeUsing 2.0
{% for page in site.pages %}
    {% if page.layout == 'java-tutorials' %}
     // do some work
    {% endif %}
{% endfor %}
{% assign tutorials = (site.pages | where: "layout" , "java-tutorials") %}
{% for page in tutorials %}
     // do some work
{% endfor %}

These are two great updates, kudos to the Jekyll team!