按 Liquid 和 Jekyll 中修改后的变量排序
Sort by a modified variable in Liquid and Jekyll
我想对 Jekyll 中的 collection 进行排序。按标题排序当然很容易。
<ul>
{% for note in site.note | sort: "title" %}
<li>{{note.path | git_mod }}: {{ note. title }}</li>
{% endfor %}
</ul>
我想按日期排序。但是由于 collections 没有日期,我有一个自定义的 Liquid 过滤器,它采用项目的路径,并在 Git 中获取其最后修改时间。您可以在上面的代码中看到,我将路径传递给 git_mod
。我可以验证这是否有效,因为当我打印出列表时,我得到了正确的上次修改时间,而且它是一个完整的日期。 (实际我也是传给date_as_string
。)
但我无法按该值排序,因为 Liquid 不知道它,因为它是 site.note
collection 中每个项目中已有的值。我如何按该值排序?我在想这样的事情,但它不起作用:
<ul>
{% for note in site.note | sort: path | date_mod %}
<li>{{note.path | git_mod }}: {{ note. title }}</li>
{% endfor %}
</ul>
我也尝试过以下变体:{% for note in site.note | sort: (note.path | git_mod) %}
None 个会抛出错误,但 none 个也能正常工作。
在这种情况下,您可以使用 Jekyll hooks。
您可以创建一个 _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
然后您将能够按 git_mod
键
排序
{% assign sortedNotes = site.note | sort: 'git_mod' %}
{% for note in sortedNotes %}
....
请注意,您不能在 for 循环中 sort
。您首先需要在 assign
中 sort
,然后 loop
。
我想对 Jekyll 中的 collection 进行排序。按标题排序当然很容易。
<ul>
{% for note in site.note | sort: "title" %}
<li>{{note.path | git_mod }}: {{ note. title }}</li>
{% endfor %}
</ul>
我想按日期排序。但是由于 collections 没有日期,我有一个自定义的 Liquid 过滤器,它采用项目的路径,并在 Git 中获取其最后修改时间。您可以在上面的代码中看到,我将路径传递给 git_mod
。我可以验证这是否有效,因为当我打印出列表时,我得到了正确的上次修改时间,而且它是一个完整的日期。 (实际我也是传给date_as_string
。)
但我无法按该值排序,因为 Liquid 不知道它,因为它是 site.note
collection 中每个项目中已有的值。我如何按该值排序?我在想这样的事情,但它不起作用:
<ul>
{% for note in site.note | sort: path | date_mod %}
<li>{{note.path | git_mod }}: {{ note. title }}</li>
{% endfor %}
</ul>
我也尝试过以下变体:{% for note in site.note | sort: (note.path | git_mod) %}
None 个会抛出错误,但 none 个也能正常工作。
在这种情况下,您可以使用 Jekyll hooks。
您可以创建一个 _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
然后您将能够按 git_mod
键
{% assign sortedNotes = site.note | sort: 'git_mod' %}
{% for note in sortedNotes %}
....
请注意,您不能在 for 循环中 sort
。您首先需要在 assign
中 sort
,然后 loop
。