Sort Jekyll Pages and Posts

Liquid isn’t the most verbose language. However, it’s the templating language that powers Jekyll, so learning its syntax and capabilities is essential when creating Jekyll pages. In this post I’ll show a technique for sorting Jekyll pages and posts by combining and sorting Liquid arrays.

The Problem

I needed a way to output a sorted array that contained Jekyll pages and posts that contained a “featured” tag. For example, the following would be the YAML front matter for an example page and post:

---
layout: page
title: Page1
tags: [featured]
featuredOrder: 1
---
...
---
layout: post
title: Post1
tags: [featured]
featuredOrder: 2
---
...

The goal was to output content from an array that contained these items sorted in ascending order based on the featuredOrder. Jekyll offers helpful site variables like site.pages and site.posts but there isn’t a variable that includes both.

The Solution

I aggregated all posts and tags with a “featured” tag to a “featuredItems” array and sorted it based on the “featuredOrder”:

{% assign featuredItems = site.tags.featured %}
{% for page in site.pages %}
    {% if page.tags contains "featured" %}
        {% assign featuredItems = featuredItems | push: page %}
    {% endif %}
{% endfor %}

{% assign featuredItems = featuredItems | sort: "featuredOrder" %}

{% for item in featuredItems %}
    {{ item.title }}
{% endfor %}

This outputs “Page1 Post1” from above, which was the desired output and currently in use to render the content on my homepage.