-
Notifications
You must be signed in to change notification settings - Fork 7
/
site_menus.rb
102 lines (90 loc) · 2.9 KB
/
site_menus.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# encoding: utf-8
#
# Jekyll site menus.
# https://github.com/MrWerewolf/jekyll-site-menus
#
# Copyright (c) 2012 Ryan Seto <mr.werewolf@gmail.com>
# Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
#
# Place this script into the _plugins directory of your Jekyll site.
#
require 'uri'
module Jekyll
class SiteMenus < Liquid::Tag
def initialize(tag_name, menu_name, tokens)
super
@menu_name = menu_name.strip!
end
def render(context)
site = context.registers[:site]
menu = site.config['menus'][@menu_name]
level = 1
renderMenu(context, menu, level)
end
def renderMenu(context, menu, level)
indent = " " * (level - 1)
output = "#{indent}"
isFirstLvl = level == 1
# Give this menu an id attribute if we're on the first level.
if (isFirstLvl)
output += "<ul id=\"#{@menu_name}-menu\" class=\"menu level-#{level}\">\n"
else
output += "<div class=\"sub-menu level-#{level}\"><ul class=\"menu sub-menu level-#{level}\">\n"
end
indent = " " * (level)
menu.each do | item |
item.each do | name, value |
if (value.kind_of? String)
# Render the menu item
output += "#{indent}<li>\n"
output += renderMenuItem(context, name, value, level)
output += "#{indent}</li>\n"
elsif (value.kind_of? Array and value.size > 0)
output += "#{indent}<li>\n"
if (value[0].kind_of? String)
output += renderMenuItem(context, name, value[0], level)
submenu = value [1..value.size]
else
submenu = value
end
# Render the sub-menu
output += renderMenu(context, submenu, level + 1)
output += "#{indent}</li>\n"
end
end
end
indent = " " * (level - 1)
if (isFirstLvl)
output += "#{indent}</ul>\n"
else
output += "#{indent}</ul></div>\n"
end
end
def renderMenuItem(context, name, value, level)
page_url = context.environments.first["page"]["url"]
uri = URI(value)
# Figure out if our menu item is currently selected.
selected = false
unless (uri.absolute?)
base_path= uri.path[-1, 1] == '/' ? uri.path : File.dirname(uri.path)
path_parts = base_path.split('/')
if (path_parts.size > 0)
selected = (/^#{base_path}/ =~ page_url) != nil
elsif (value == '/' and page_url == '/index.html')
selected = true
else
selected = value == page_url
end
end
indent = " " * level
output = "#{indent} <a href=\"#{URI.escape(value)}\""
if (selected)
output += " class=\"selected\""
end
output += ">"
output += name
output += "</a>\n"
end
end
Liquid::Template.register_tag('menu', Jekyll::SiteMenus)
end