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

8
在Jekyll中,我希望我的首页按日期分组列出最近的文章,如下所示:
2013年9月6日
- 文章1 - 文章2 - 文章3
2013年9月5日
- 文章1 - 文章2
基本上,当循环中的文章来自先前处理的不同日期时,我只想输出日期标题。我尝试通过测试循环中下一篇文章是否与上一篇文章的日期匹配,并仅在它们不匹配时显示日期头来实现此目的。这是我的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 %}

如果我使用post.date | date: "%m-%d-%Y"而不是仅仅使用post.date,它会工作并且帖子会被分组在一起,但仅当这些帖子具有完全相同的日期和时间(不仅仅是同一月份的同一天)。这就是为什么我添加了更具体的post.date | date: "%m-%d-%Y"

有何想法?非常感谢您的帮助!

3个回答

7

通过修改这里的存档解决方案找到了答案: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 %}

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

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


4

替代方案:

直接以您想要在最后显示的格式捕获日期。
(这里是:%A, %B %d, %Y --> Monday, April 30, 2012)

那么您就不需要经常使用| date:了:

{% for post in site.posts %}
  {% capture currentdate %}{{post.date | date: "%A, %B %d, %Y"}}{% endcapture %}
  {% if currentdate != thedate %}
    <h2>{{ currentdate }}</h2>
    {% capture thedate %}{{currentdate}}{% endcapture %} 
  {% endif %}
    <h3><a href="{{ post.url }}">{{ post.title }}</a></h3>
{% endfor %}

生成的HTML代码如下:
<h2>Monday, April 30, 2012</h2>
<h3><a href="/2012/04/30/foo/">Foo</a></h3>
<h2>Friday, March 09, 2012</h2>
<h3><a href="/2012/03/09/bar/">Bar</a></h3>
<h3><a href="/2012/03/09/baz/">Baz</a></h3>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接