How To Sort For Loops With The Liquid Templating Language

by Rubie Tiburcio


Sorting an array of items could be handled with a powerful tag, nested_sort, in Liquid Templating Language.

nested_sort, by default, sorts the array of items in ascending order.

{% assign events = item_types.event.published_items | nested_sort:"contents.starts_at" %}

This line of code stores the array of published events items into the events object in ascending order based on event's start date, contents.starts_at.

When you iterate through each item in the events object, each item will be sorted in ascending order based on the set event start date's value.

{% for event in events %}   
  ... 
  <HTML tags>
  {{event.contents.starts_at | date: "%A, %B %D, %Y"}}
  ... 
{% endfor%}

To sort the items in descending order, simply add the filter, | reverse, after the nested_sort tag.

{% assign events = item_types.event.published_items | nested_sort:"contents.starts_at" | reverse %}

The returned result should now display all items based on the desired sort order.

Ready to try it yourself and build something cool?

Get started »