Sort collection by two fields

Sort a Liquid collection by 2 different fields at once and override weight sorting when weighting is used.


Scenario; let’s say you have a list of people and generally you want to list them by their ‘Company’ names (alphabetically). But some people have an additional ‘Status’ type and you want to list those people first in the list - but still alphabetically by their company names.

  1. We could do something like this, where-by calling the module 'People' to a Liquid collection using the sortBy: "Company" parameter for the initial sorting by 'Company' field.

    Then, pass that collection to a Liquid variable and apply the Liquid sort filter to sort the collection by a second 'Status' field:

    <!-- Treehouse CODE v1.0.0 -->
    {% component source: "People", layout: "", sortBy: "Company", sortOrder: "ASC", collectionVariable: "myItems", type: "module" %}
    {% assign sorted = myItems.items | sort: 'Status' %}
  2. Finally, render the collection via a for loop.

    (you can still use list layouts with this method too, by setting the component to use object: "collection" and placing the below code in your list layout instead)

    <!-- Treehouse CODE v1.0.0 -->
    {% for s in sorted %}
    {% endfor %}
  3. TIP: To reverse the Liquid sorting use an additional reverse filter in part 1 above, eg:

    <!-- Treehouse CODE v1.0.0 -->
    {% assign sorted = myItems.items | sort: 'Status' | reverse %}

Comments or questions? Head over to the Treepl CMS forum to discuss with the community.