section-link-highlight.lua (1814B)
1 -- Highlights the link to the current page/section in the navigation menu 2 -- If you have <a href="/about">, it will add a CSS class to it on page site/about.html 3 -- It assumes you are using relative links 4 -- 5 -- Sample configuration: 6 -- [plugins.active-link-hightlight] 7 -- active_link_class = "active" 8 -- nav_menu_selector = "nav" 9 -- 10 -- Minimum soupault version: 1.6 11 -- Author: Daniil Baturin 12 -- License: MIT 13 14 active_link_class = config["active_link_class"] 15 nav_menu_selector = config["selector"] 16 17 if (not active_link_class) then 18 Log.warning("active_link_class option is not set, using default (\"active\")") 19 Plugin.fail() 20 active_link_class = "active" 21 end 22 23 if (not nav_menu_selector) then 24 Log.warning("nav_menu_selector option is not set, using default (\"nav\")") 25 nav_menu_selector = "nav" 26 end 27 28 menu = HTML.select_one(page, nav_menu_selector) 29 if (not menu) then 30 Plugin.exit("No element matched selector " .. nav_menu_selector .. ", nothing to do") 31 end 32 33 34 links = HTML.select(menu, "a") 35 36 local index = 1 37 while links[index] do 38 link = links[index] 39 40 href = HTML.get_attribute(link, "href") 41 42 if not href then 43 -- Link has no href attribute, ignore 44 else 45 href = strlower(href) 46 47 -- Remove leading and trailing slashes 48 href = Regex.replace_all(href, "(\\/?$|^\\/)", "") 49 page_url = Regex.replace_all(page_url, "(\\/?$|^\\/)", "") 50 51 -- Normalize slashes 52 href = Regex.replace_all(href, "\\/+", "\\/") 53 54 -- Edge case: the / link that becomes "" after normalization 55 -- Anything would match the empty string and higlight all links, 56 -- so we handle this case explicitly 57 if ((page_url == "") and (href == "")) 58 or ((href ~= "") and Regex.match(page_url, "^" .. href)) 59 then 60 HTML.add_class(link, active_link_class) 61 end 62 end 63 64 index = index + 1 65 end