2
votes

I have a collection in Jekyll which I want to sort. Sorting by title is easy of course.

<ul>
{% for note in site.note | sort: "title" %}
<li>{{note.path | git_mod }}: {{ note. title }}</li>
{% endfor %}
</ul>

I want to sort by date. But since collections don't have a date, I have a custom Liquid filter which takes the path of the item, and gets its last modified time in Git. You can see that in the code above, where I pass the path to git_mod. I can verify that this works, because when I print out the list, I get the correct last modified times, and it is a full date. (In practice, I also pass it to date_as_string.)

But I can't sort by that value because Liquid doesn't know about it, since it is a value already in each item in the site.note collection. How can I sort by that value? I was thinking something like this, but it doesn't work:

<ul>
{% for note in site.note | sort: path | date_mod %}
<li>{{note.path | git_mod }}: {{ note. title }}</li>
{% endfor %}
</ul>

I've also tried variants like: {% for note in site.note | sort: (note.path | git_mod) %}

None of these throw an error, but none of them work either.

1
Would you mind sharing the code for git_mod? I'm trying to do the same thing - moondaisy

1 Answers

2
votes

This is a case where you can use Jekyll hooks.

You can create a _plugins/git_mod.rb

Jekyll::Hooks.register :documents, :pre_render do |document, payload|

  # as posts are also a collection only search Note collection
  isNote = document.collection.label == 'note'

  # compute anything here
  git_mod = ...

  # inject your value in dacument's data
  document.data['git_mod'] = git_mod

end

You then will be able to sort by git_mod key

{% assign sortedNotes = site.note | sort: 'git_mod' %}
{% for note in sortedNotes %}
....

Note that you cannot sort in a for loop. You first need to sort in an assign, then loop.