如何在Jekyll的主页上按日期分组帖子?

jer*_*ito 8 ruby liquid jekyll

在Jekyll,我希望我的主页列出按日期分组的最新帖子,如下所示:

2013年9月6日

  • 发布1
  • 发布2
  • 邮政3

2013年9月5日

  • 发布1
  • 发布2

基本上,我只想在循环中的帖子与之前处理的日期不同时吐出日期标题.我试图通过测试for循环中的下一篇文章是否匹配上一篇文章的日期来做到这一点,并且只有当它没有时才显示日期标题.这就是我的Liquid模板的样子:

---
layout: default
title: Home Page
---

{% assign thedate = '' %}

{% for post in site.posts %}

    {% if thedate != post.date | date: "%m-%d-%Y" %}
        <h2>{{ post.date | date: "%A, %B %e, %Y" }}</h2>
    {% endif %}

    {% assign thedate = post.date | date: "%m-%d-%Y" %}

    <h3 class="headline"><a href="{{ post.url }}">{{ post.title }}</a></h3>
    {{ post.content }}
    <hr>

{% endfor %}
Run Code Online (Sandbox Code Playgroud)

如果不是使用post.date | date: "%m-%d-%Y"我而是简单地post.date说它有效,并且帖子被组合在一起,但仅当帖子具有完全相同的日期和时间(而不仅仅是该月的同一天).这就是我添加更具体的原因post.date | date: "%m-%d-%Y".

有任何想法吗?非常感谢我们的帮助!!

jer*_*ito 6

通过修改档案解决方案找到答案:http://www.mitsake.net/2012/04/archives-in-jekyll/

这是有效的代码:

layout: default
title: Home Page
---

{% for post in site.posts %}

    {% capture day %}{{ post.date | date: '%m%d%Y' }}{% endcapture %}
    {% capture nday %}{{ post.next.date | date: '%m%d%Y' }}{% endcapture %}

    {% if day != nday %}
        <h5 class="date">{{ post.date | date: "%A, %B %e, %Y" }}</h5>
    {% endif %}
    {{ post.content }}
    <hr>

{% endfor %}
Run Code Online (Sandbox Code Playgroud)


Tre*_*vor 5

这些以前的解决方案是绕过以前版本的 Jekyll 缺点的绝妙而优雅的方式,但幸运的是,在 2016 年末,Jekyll 添加了一个group_by_exp过滤器,可以更干净地做到这一点。

{% assign postsByDay = 
site.posts | group_by_exp:"post", "post.date | date: '%A, %B %e, %Y'" %}

{% for day in postsByDay %}
  <h1>{{ day.name }}</h1>
    <ul>
      {% for post in day.items %}
        <li><a href="{{ post.url }}">{{ post.title }}</a></li>
      {% endfor %}
    </ul>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

文档可以在Jekyll 模板页面找到