Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add plugin for generating tag pages automatically #84

Open
wants to merge 1 commit into
base: gh-pages
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions _plugins/auto_gen_tags.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# This plugin generates tag pages automatically after saving posts.
#
# To enable this plugin, please do the following steps:
# 1, Create a dir named 'tags' under the root dir.
# 2. Create a layout, named `_layouts/tag.html,` for tag pages. For example,
# ---
# layout: default
# ---
# <h1>
# Tag: {{ page.tag }}
# </h1>
# <ul>
# {% for post in site.posts %}
# {% if post.tags contains page.tag %}
# <li>
# <a href="{{ post.url }}">{{ post.title }}</a>
# ({{ post.date | date_to_string }})<br>
# </li>
# {% endif %}
# {% endfor %}
# </ul>
#
# 3. Comment out the `return` statement in the next line.
return
# 4. Start jekyll server at local, and the server will parse all posts and
# generate tag pages to the `tags/` dir. The tag pages are also generated
# on-the-fly after saving posts if jekyll server is running at background.

Jekyll::Hooks.register :posts, :post_write do |post|
all_existing_tags = Dir.entries("tags")
.map { |t| t.match(/(.*).md/) }
.compact.map { |m| m[1] }

tags = post['tags'].reject { |t| t.empty? }
tags.each do |tag|
generate_tag_file(tag) if !all_existing_tags.include?(tag)
end
end

def generate_tag_file(tag)
File.open("tags/#{tag}.md", "wb") do |file|
file << "---\nlayout: tag\ntitle: \"Tag: #{tag}\"\ntag: #{tag}\n---\n"
end
end