Skip to content

Instantly share code, notes, and snippets.

@fahrinh
Forked from nistude/category_list.rb
Created November 15, 2011 11:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fahrinh/1366833 to your computer and use it in GitHub Desktop.
Save fahrinh/1366833 to your computer and use it in GitHub Desktop.
A category list tag for jekyll
# place this file in your plugins directory and add the tag to your sidebar
#$ cat source/_includes/custom/asides/categories.html
#<section>
# <h1>Categories</h1>
# <ul id="categories">
# {% category_list %}
# </ul>
#</section>
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)
@davidxia
Copy link

I had trouble with ampersands in category names, eg 'Tech & Prod'. The above generated a url that was missing the '-and-' that Jekyll creates. I found this worked

category_url = File.join(category_dir, category.to_url)

@yottanami
Copy link

It does not support non English category names, How can I change it to support other Unicode languages?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment