Octopress - Category List Plug-in


Programming in Ruby tutorials and examples

Octopress - Category List Plug-in

MaxCDN Content Delivery Network

I have just switched two blogs over to use Octopress, both dotnetguy.co.uk and also paz.am/blog.

One thing that was missing “out of the box” was the ability to include a list of categories in the sidebar with a link. Fortunately Octopress (well actually Jekyll) is written in such away that creating a plug-in to do this is very simple.

Firstly we need to write a little ruby code. Add a file to the plugins directory called category_list_tag.rb. This plug-in will take the category data from the site and generate list items for each category. On line 17 the category_list tag is then registered and made available to the liquid templating engine.

category_list_tag.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
module Jekyll
  class CategoryListTag < Liquid::Tag
    def render(context)
      html = ""
      categories = context.registers[:site].categories.keys
      categories.sort.each do |category|
        posts_in_category = context.registers[:site].categories[category].size
        category_dir = context.registers[:site].config['category_dir']
        category_url = File.join(category_dir, category.gsub(/_|\P{Word}/, '-').gsub(/-{2,}/, '-').downcase)
        html << "<li class='category'><a href='/#{category_url}/'>#{category} (#{posts_in_category})</a></li>\n"
      end
      html
    end
  end
end

Liquid::Template.register_tag('category_list', Jekyll::CategoryListTag)

Now we need to create the category list (category_list.html) template in source/_includes/asides. We now use the “category_list” tag we registered in the plug-in above.

category_list.html
1
2
3
4
5
6
<section>
  <h1>Categories</h1>
  <ul id="categories">
    {% category_list %}
  </ul>
</section>

Finally we just need to add the new sidebar template to the default_asides configuration within the _config.yml.

_config.yml
1
default_asides: [asides/category_list.html, asides/recent_posts.html, asides/twitter.html, asides/delicious.html, asides/pinboard.html, asides/googleplus.html]

And that’s all she wrote! I think Octopress / Jekyll is an excellent blog engine / static site generator, and being able to hack away and write simple plug-ins quickly makes it my number one choice… for now.

Comments