bdunagan

Brian Dunagan

October 15 2021
Jekyll Tip: Adding Years and Post Counts using Liquid

After 13 years and 177 posts, this blog is a bit long for a single scrolling index, so I added years to delineate the content as well as post count per year.

That involved a bit of programming in Liquid, a template language created by Shopify and used by Jekyll. Liquid does not expose support for hash creation, even though Jekyll can provide hashes like site. Fortunately, it supports group_by_exp expressions, available in v3.4+.

Below is the code I used:

<ul class="posts">
  {% assign posts_per_year = site.posts | group_by_exp: "post", "post.date | date: '%Y'" %}
  {% for post in site.posts %}
    {% assign year = post.date | date: "%Y" %}
    {% for current_year in posts_per_year %}
      {% if last_year != year and current_year.name == year %}
        <li class="year">{{ year }} - {{ current_year.size }}</li>
      {% endif %}
    {% endfor %}
    {% assign last_year = year %}

    <li>
      <span class="datetime muted" data-time="{{ post.date }}">{{ post.date | date: "%B %-d %Y" }}</span>
      <a href="{{ post.url }}">{{ post.title }}</a>
      <p>{{ post.description }}</p>
    </li>
  {% endfor %}
</ul>

I’ve been using Jekyll for eight years now. In 2013, I converted from Wordpress’s database-driven approach to Jekyll’s static HTML-generated approach: “Why I moved from Wordpress to Jekyll”. It continues to work well.

And for those who use Jekyll, you can post Liquid as text in a post by using {% raw %}{% endraw %}.

Building Deep, Scalable Customer Relationship Management Tools How to Protect Cloud Storage with Retrospect Backup's Cloud Data Protection
LinkedIn GitHub Email