Franz
Franz

Reputation: 283

Jekyll display collection by category

I'm having trouble figuring out how to sort the content of a collection by category. I've found a very similar question on how to sort posts by category but it doesn't seem to work with collections Jekyll display posts by category.

Let's say I have a collection called 'cars' with two categories: 'old' and 'new'. How can I display only cars with the category 'old'?

Upvotes: 15

Views: 5976

Answers (1)

David Jacquel
David Jacquel

Reputation: 52799

You can sort, group or filter collection like any other object like page or posts.

_my_collection/mustang.md

---
category: 'old'
abbrev: tang
---
mustang content

_my_collection/corvette.md

---
category: 'new'
abbrev: vet
---
corvette content

Filtering

{% assign newcars = site.my_collection | where: "category", "new" %}

Sorting

{% assign allcarssorted = site.my_collection | sort: "category" %}

Grouping

{% assign groups = site.my_collection | group_by: "category" | sort: "name" %}

This groups your cars and then sort groups by name that is the category.

{% for group in groups %}
    {{ group.name }}
    {% for item in group.items %}
        {{item.abbrev}}
    {%endfor%}
{%endfor%}

Upvotes: 25

Related Questions