I changed the tags design recently, as a follow up, I implemented archive pages for tags today. Now you can click on any tag and get a collection of posts for that tag! In this post, I’m going to explain how to add generated tag pages to a Jekyll blog.

To do this, we need to create a Jekyll plugin for generating our tags pages.

I used a snippet from this webpage: http://brizzled.clapper.org/blog/2010/12/20/some-jekyll-hacks/

_plugins/tags.rb

module Jekyll
  class TagIndex < Page
    def initialize(site, base, dir, tag)
      @site = site
      @base = base
      @dir = dir
      @name = 'index.html'
      self.process(@name)
      self.read_yaml(File.join(base, '_layouts'), 'tag_index.html')
      self.data['tag'] = tag
      tag_title_prefix = site.config['tag_title_prefix'] || 'Posts Tagged &ldquo;'
      tag_title_suffix = site.config['tag_title_suffix'] || '&rdquo;'
      self.data['title'] = "#{tag_title_prefix}#{tag}#{tag_title_suffix}"
    end
  end
  class TagGenerator < Generator
    safe true
    def generate(site)
      if site.layouts.key? 'tag_index'
        dir = site.config['tag_dir'] || 'tag'
        site.tags.keys.each do |tag|
          write_tag_index(site, File.join(dir, tag), tag)
        end
      end
    end
    def write_tag_index(site, dir, tag)
      index = TagIndex.new(site, site.source, dir, tag)
      index.render(site.layouts, site.site_payload)
      index.write(site.dest)
      site.pages << index
    end
  end
end

This creates a directory for every tag with an index.html file in the “tag” directory. The tag directory can be configured in your _config.yml file with the tag_dir key. The tag page’s title can be customized with tag_title_prefix and tag_title_suffix.

Now we also need a layout file to generate the pages. Something like this:

_layouts/tag_index.html

---
layout: default
---


<div class="home">
  <h1 class="page-heading">Posts for #{{page.tag}}</h1>
  <ul class="post-list">
    {%- for post in site.posts -%}
      {% for tag in post.tags %}
        {% if tag == page.tag %}
          <li>
            <h3>
              <a class="post-link" href="{{ post.url | relative_url }}">
                {{ post.title | escape }}
              </a>
            </h3>
            {%- if site.show_excerpts -%}
              {{ post.excerpt }}
            {%- endif -%}
          </li>
        {% endif %}
      {% endfor %}
    {% endfor %}
  </ul>
</div>

And that’s it! For every tag you add to any blog post, a page is generated for that tag.

Try it by clicking/tapping an one of the tags at the top.