How to add tags on Jekyll

October 18, 2016

I added tags on my top page and every posts without plugin.

Today, I’ll introduce how to add tags on Jekyll.

Step 1

Add tags on your post. For example, this article has tags like this.

tags: Jekyll Ruby

Step 2

Then each post has tags variable. You can access these tags by the following code from index.html.

{% raw %}<div class="home">
  <h1 class="page-heading">Posts</h1>
  <ul class="post-list">
    {% for post in site.posts %}
        <span class="post-meta">{{ | date: "%b %-d, %Y" }}</span>
          <a class="post-link" href="{{ post.url | prepend: site.baseurl }}">{{ post.title | escape }}</a>
        {% for tag in post.tags %}
          <span class="label">{{tag}}</span>
        {% endfor %}
    {% endfor %}
  <p class="rss-subscribe">subscribe <a href="{{ "/feed.xml" | prepend: site.baseurl }}">via RSS</a></p>
</div>{% endraw %}

Step 3

In step 2, you can access tags via post in site.posts. From each page, you can access it via page variable. See the following example.

{% raw %}
<article class="post" itemscope itemtype="">
  <header class="post-header">
    <p class="post-meta">
        datetime="{{ | date_to_xmlschema }}"
        >{{ | date: "%b %-d, %Y" }}</time
    <h1 class="post-title" itemprop="name headline">
      {{ page.title | escape }}
    {% for tag in page.tags %}
    <span class="label">{{tag}}</span>
    {% endfor %}

  <div class="post-content" itemprop="articleBody">
    {{ content }}
{% endraw %}

Step 4

Finally, you just add some cool styles to tags.

Entire code is here, please use that as reference.

© 2021, Yosuke Saito