In Jekyll, how to show “posts from last week”

后端 未结 3 1246
暖寄归人
暖寄归人 2021-01-20 05:35

I\'m not sure to get the liquid syntax to help me pull posts that were published during the same week as the build date. Is that possible?

There are simpler ways to

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-20 06:03

    The above solution works, but doesn't span years.

    So I utilized the concepts and came up with a simpler and more flexible solution for filtering for a timeframe (which can be any variable time span of seconds, hours, days, weeks, or months). My solution has fewer variables, and less logic.

    Liquid date/time uses unix timestamp (%s = seconds since 1970). So I kept the timeframe in seconds and do the conversion for the length of time. 86400 = 1 day, 604800 = 1 wk, 2678400 = 31 days, ... and so on.

    The code also assumes your posts use last_modified_at in your post frontmatter. You could substitute for post.date if you're not.

    Simple Solution

    List posts within last week

    {% assign timeframe = 604800 %}
    
    {% for post in site.posts %}
      {% assign post_in_seconds = post.last_modified_at | date: "%s" | plus: 0 %}
      {% assign recent_posts = "now" | date: "%s" | minus: timeframe  %}
    
      {% if post_in_seconds > recent_posts %}
        {{ post.title }}
      {% endif %}
    {% endfor %}
    

    Alternative

    List posts within timeframe and flag new or modified

    This code will list all posts to within a limit and flag an posts as new or modified in timeframe. Length of list is limited to maxposts. Note: css class is designed to utilize Bootstrap, remove/edit to your liking.

    • timeframe 2419200 = seconds in 4 weeks
    • maxposts = 10
    • label_FOOBAR just clean way to handle html with liquid

    Example Results with new/modified flags & dates

    Code

    {% assign timeframe = 2419200 %}
    {% assign maxposts = 10 %}
    {% assign date_format = site.minima.date_format | default: "%m/%d" %}
    
    
      {% for post in site.posts limit: maxposts %} {% assign post_in_seconds = post.last_modified_at | date: "%s" | plus: 0 %} {% assign recent_posts = "now" | date: "%s" | minus: timeframe %} {% assign post_updated = post.last_modified_at | date: date_format %} {% capture post_date %}{{ post.date | date: date_format }}{% endcapture %} {% if post_in_seconds > recent_posts %} {% capture label_new %}new{% endcapture %} {% if post.last_modified_at > post.date %} {% assign label_new = '' %}{% comment %}Clear NEW if modified{% endcomment %} {% capture label_updated %}Updated {{ post_updated }}{% endcapture %} {% endif %} {% endif %}
    • {{ post_date }} {{ post.title | escape }} {{ label_new }}{{ label_updated }}

    • {% assign post_date = '' %} {% assign label_updated = '' %} {% endfor %}

提交回复
热议问题