Created
March 7, 2012 18:19
-
-
Save azsromej/1994881 to your computer and use it in GitHub Desktop.
Jekyll generator plugin to group posts by month for archives page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
layout: default | |
title: Archives | |
--- | |
<h1>{{ page.title }}</h1> | |
<div class="archives"> | |
{% for month in page.months %} | |
<h2>{{ month | date:"%B" }} <small>{{ month | date:"%Y" }}</small></h2> | |
<ul> | |
{% for post in page.posts_by_month[month] %} | |
<li><a href="{{ post.url }}">{{ post.title | truncate:65 }}</a></li> | |
{% endfor %} | |
</ul> | |
{% endfor %} | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Generates a single archives.html page in site root that lists all posts by month. | |
# | |
# Learned from: | |
# https://github.com/mojombo/jekyll/wiki/Plugins | |
# https://gist.github.com/707909 | |
# | |
# | |
module Jekyll | |
class ArchivePage < Page | |
def initialize(site, months, posts_by_month) | |
@site = site | |
@base = site.source | |
# I simply write the archives.html file in the _site root | |
@dir = "/" | |
@name = "archives.html" | |
self.process(@name) | |
self.read_yaml(File.join(@base, '_layouts'), 'archives.html') | |
# array of Times, normalized to year and month | |
self.data['months'] = months | |
# hash keyed on normalized times, mapped to array of posts | |
self.data['posts_by_month'] = posts_by_month | |
end | |
end | |
class ArchiveGenerator < Generator | |
safe true | |
def group_by_month(posts) | |
months = [] | |
posts_by_month = {} | |
posts.reverse.each do |post| | |
key = Time.utc(post.date.year, post.date.month) | |
if posts_by_month.has_key?(key) | |
posts_by_month[key] << post | |
else | |
posts_by_month[key] = [post] | |
months << key | |
end | |
end | |
return [months,posts_by_month] | |
end | |
def generate(site) | |
archive_data = group_by_month(site.posts) | |
months = archive_data[0] | |
posts_by_month = archive_data[1] | |
archives = ArchivePage.new(site, months, posts_by_month) | |
archives.render(site.layouts, site.site_payload) | |
archives.write(site.dest) | |
site.pages << archives | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
produces an archives page that looks like: http://romej.com/archives