首页 文章

按Liquid和Jekyll中的修改变量排序

提问于
浏览
1

我在Jekyll有一个我想要排序的集合 . 按 Headers 排序当然很容易 .

<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 . )

但我可以't sort by that value because Liquid doesn't知道它,因为它已经是 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) %}

这些都没有抛出错误,但它们都没有工作 .

1 回答

  • 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 . 首先需要 sort assign ,然后 loop .

相关问题