【问题标题】:Sort by a modified variable in Liquid and Jekyll按 Liquid 和 Jekyll 中的修改变量排序
【发布时间】:2016-07-15 19:10:49
【问题描述】:

我在 Jekyll 中有一个收藏,我想对其进行排序。按标题排序当然很容易。

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

我想按日期排序。但是由于集合没有日期,我有一个自定义的 Liquid 过滤器,它采用项目的路径,并在 Git 中获取其最后修改时间。你可以在上面的代码中看到,我将路径传递给git_mod。我可以验证这是否有效,因为当我打印出列表时,我得到了正确的最后修改时间,并且它是一个完整的日期。 (实际上,我也将它传递给date_as_string。)

但我无法按该值排序,因为 Liquid 不知道它,因为它是 site.note 集合中每个项目中已经存在的值。如何按该值排序?我在想这样的事情,但它不起作用:

<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) %}

这些都不会引发错误,但它们都不起作用。

【问题讨论】:

  • 您介意分享git_mod 的代码吗?我正在尝试做同样的事情

标签: jekyll liquid


【解决方案1】:

这种情况下你可以使用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 build --incremental 似乎在重建后丢失了日期,但这肯定不是这个答案的错。
猜你喜欢
  • 2017-09-03
  • 2016-11-16
  • 1970-01-01
  • 2012-02-21
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多