Skip to content

Instantly share code, notes, and snippets.

@sillydeveloper
Last active August 29, 2015 14:12
Show Gist options
  • Save sillydeveloper/09e880f7643de5c15d89 to your computer and use it in GitHub Desktop.
Save sillydeveloper/09e880f7643de5c15d89 to your computer and use it in GitHub Desktop.
Jekyll navigation generator for bootstrap
# Auto-generates navigation -- bootstrap based
# <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
# <ul class="nav navbar-nav">
# {% generate_navigation %}
# </ul>
# </div><!-- /.navbar-collapse -->
# based on https://gist.github.com/jamtur01/2759606
require 'pathname'
module Jekyll
class Page
def source_path
File.join(@dir, @name).sub(%r{^/*},'')
end
def parent
@dir.sub(%r{^/*},'')
end
end
class IncludeListingTag < Liquid::Tag
def initialize(tag_name, markup, tokens)
super
end
def add_item(page)
if page.index?
title = page.parent
else
title = page.basename
end
# Try to read title from source file
source_file = File.join(@source,page.source_path)
if File.exists?(source_file)
content = File.read(source_file)
if content =~ /^(---\s*\n.*?\n?)^(---\s*$\n?)/m
content = $POSTMATCH
begin
data = YAML.load($1)
rescue => e
puts "YAML Exception reading #{name}: #{e.message}"
end
end
if data['title']
title = data['title']
end
else
puts "File not found: #{source_file}"
end
s = "<li><a href=\"#{page.permalink}\">#{title}</a></li>"
end
def render(context)
site = context.registers[:site]
@source = site.source
site_pages = context.environments.first['site']['pages']
html = "<li class='dropdown'>"
list = Hash.new { |h,k| h[k] = [] }
site_pages.each do |page|
next if page.index?
if ['css', ''].include?(page.parent)
html += "<li><a href=\"#{page.permalink}\">#{page['title']}</a></li>"
else
list[page.parent.gsub('_', ' ').capitalize] << self.add_item(page)
end
end
list = list.sort
list.each { |header, subs|
html += "<li class='dropdown'><a href='#' class='dropdown-toggle' data-toggle='dropdown' role='button' aria-expanded='false'>#{header} <span class='caret'></span></a>"
html += "<ul class='dropdown-menu' role='menu'>"
subs.each { |sub| html += sub }
html += "</ul></li>"
}
html += "</ul>"
html
end
end
end
Liquid::Template.register_tag('generate_navigation', Jekyll::IncludeListingTag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment