8

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

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

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

4

3 回答 3

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 %}
于 2013-09-07T15:20:43.667 回答
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 模板页面上找到。

于 2017-04-03T17:58:47.690 回答
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>
于 2013-12-25T23:23:33.360 回答