【问题标题】:Liquid filter by date (Jekyll)按日期过滤液体 (Jekyll)
【发布时间】:2020-07-08 05:40:07
【问题描述】:

我正在尝试在 Jekyll 中按特定日期过滤帖子。例如,我想归档今天、过去 30 天以及之前的所有帖子。

但是我遇到了几个问题:

  1. 如何获取当前日期,从上午 00:01 开始
  2. 如何获取当前日期并减去 30 天
  3. 如何使用where_exp 按此日期过滤

目前我尝试做这样的事情,但这会将日期转换为字符串,并且不能在where_exp中使用:

{% capture thirty_days_ago %}{{'now' | date: '%s' | minus: 2592000 }}{% endcapture %}
{% assign last_30_days_posts = site.posts | where_exp:"post", "post.posted_on > thirty_days_ago" %}

Liquid error (line 22): comparison of Time with String failed in index.html

我可以在遍历帖子时做一个简单的检查,但在此之前我更喜欢使用过滤器。

{% capture thirty_days_ago %}{{'now' | date: '%s' | minus: 2592000 }}{% endcapture %}
{% for post in site.posts %}
    {% capture post_date %}{{ post.posted_on | date: '%s' | plus: 0 }}{% endcapture %}

    {% if job_date > thirty_days_ago %}
        {% include components/job.html job=job %}
    {% endif %}
{% endfor %}

【问题讨论】:

标签: jekyll liquid


【解决方案1】:

对于任何寻求解决方案的人;我最终编写了一个自定义过滤器:

def last_month_filter(posts)
    now = DateTime.now
    today = DateTime.new(now.year, now.month, now.day, 0, 0, 0, now.zone)
    target = today - 30

    posts.select do |post|
        postedOn = post.data['posted_on'].to_datetime

        if postedOn < today && postedOn > target
            post
        end
    end
end

用法:

{% assign last_30_days = site.posts | last_month_filter | sort:"posted_on" | reverse %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多