7

How do I loop through a Jekyll site's posts but only take action on posts where the year is equal to a specific value?

{% for post in site.posts %}
  {% if post.date.year == 2012 %}
      <p>{{ post.date }}</p>
      <p>{{ post.title }}</p>
  {% endif %}
{% endfor %}

The above does not work. What is the correct way to do this?

1 Answer 1

8

To extract the year of a date, you have to use the date filter with "%Y" (the full syntax is listed here). i.e.:

{% for post in site.posts %}
  {% capture year %}{{post.date | date: "%Y"}}{% endcapture %}
  {% if year == "2012" %}
      <p>{{ post.date }}</p>
      <p>{{ post.title }}</p>
  {% endif %}
{% endfor %}
3
  • 1
    That really works for you? I never managed to make such if condition to work. Neither yours work with Jekyll 0.11.2 and Liquid 2.3.0.
    – manatwork
    Mar 9, 2012 at 7:31
  • @manatwork Oops, it certainly appeared to work when I tested it, but I missed the fact that it didn't.... Fixed now.
    – huon
    Mar 9, 2012 at 7:41
  • So, how would you do this, but check for the existence of any post during that year? For example, if there are posts in 2008, print an h4. Oct 25, 2012 at 8:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.