Skip to content

Instantly share code, notes, and snippets.

@budparr
Last active January 21, 2024 11:10
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save budparr/0ad4a7449f9604f47eec to your computer and use it in GitHub Desktop.
Save budparr/0ad4a7449f9604f47eec to your computer and use it in GitHub Desktop.
Example Jekyll group_by filter #jekyllrb
{% comment %}
items is a collection, though I think it coule be any content type
{% endcomment %}
{% comment %} Create the group. {% endcomment %}
{% assign items_grouped = site.items | group_by: 'category' | sort: 'name' | reverse %}
{% comment %}
The above returns, for example, which is why we sort by 'name'
{"name"=>"category1_value", "items"=>[#, #, #, #, #]}{"name"=>"category2_value", "items"=>[#, #, #, #]}
{% endcomment %}
{% comment %} Loop through the groups {% endcomment %}
{% for group in items_grouped %}
{% comment %} Create the items within the groups, now sorting by the criteria you want them sorted {% endcomment %}
{% assign items = item.items | sort: 'date' | reverse %}
{% comment %} Loop through the items {% endcomment %}
{% for item in items %}
{{ item.title }}
{% endfor %}
{% endfor %}
@arkadianriver
Copy link

Excellent! I was searching for a way to use a secondary sort field resulting in single list and this does it! 👍 !!
Too bad I spent all day getting first a distinct list and using that to group and loop through items with a where clause. This is much more concise.
Also discovered today {{ variable | inspect }} to see that name and items is standard for groups
Doin' the happy dance. :O)
note.. Line 14 should be group.items rather than item.items

@yalov
Copy link

yalov commented Feb 24, 2017

<p>{{ category_posts.name }}</p>
is
["category_name"] .

How to get name without [" and "] ? Is there .first somewhere?

{{ category_posts.name | remove: '["' | remove: '"]' }} is not fair play.

@seungwubaek
Copy link

<p>{{ category_posts.name }}</p>
is
["category_name"] .

How to get name without [" and "] ? Is there .first somewhere?

{{ category_posts.name | remove: '["' | remove: '"]' }} is not fair play.

Is this group_by: array problem solved?

It still occurred when {{ site.posts | group_by: categories }}. Not category.

Anyone know this? please help

@digitigradeit
Copy link

It's better to do itemObj.name | remove: '[' | remove: ']' | remove: '"' | trim otherwise it fails with posts with no (blank) categories

But even with Jekyll 4.3.3 (as of 2024-06-21) it's still an issue :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment