Jekyll/Liquid Templating: How to group blog posts by year?

前端 未结 8 1292
無奈伤痛
無奈伤痛 2020-11-28 04:45

I\'m rewriting my blog to use Jekyll. Jekyll uses the Liquid templating language so it makes it a little more difficult to learn how to customize.

I\'d like to group

8条回答
  •  日久生厌
    2020-11-28 04:59

    It can be done with much, much less Liquid code than in the existing answers:

    {% for post in site.posts %}
      {% assign currentdate = post.date | date: "%Y" %}
      {% if currentdate != date %}
        
  • {{ currentdate }}
  • {% assign date = currentdate %} {% endif %}
  • {{ post.title }}
  • {% endfor %}

    This will return exactly the HTML specified in your question:

  • 2013
  • foo
  • 2012
  • bar
  • baz

  • However, this is not the optimal solution, because the year numbers are "only" list items as well.
    It's not much more Liquid code to put the year into a headline and to begin a new

      for each year's posts:

      {% for post in site.posts %}
        {% assign currentdate = post.date | date: "%Y" %}
        {% if currentdate != date %}
          {% unless forloop.first %}
    {% endunless %}

    {{ currentdate }}

      {% assign date = currentdate %} {% endif %}
    • {{ post.title }}
    • {% if forloop.last %}
    {% endif %} {% endfor %}

    The generated HTML:

    2013

    2012


    You can also group by month and year instead (so that the headlines are February 2012, January 2012 and so on).

    To do this, you just need to replace date: "%Y" (in the second line of both above examples) by date: "%B %Y".
    (%B is the full month name, see the documentation)

提交回复
热议问题