|
| 1 | +# Jekyll Out Modder - Allows for mangling/modding the HTML output |
| 2 | +# |
| 3 | +# This is combined in a single plugin/filter to reduce the NokoGiri dom |
| 4 | +# parsing to just once per page/content. |
| 5 | +# |
| 6 | +# - Automatically adds rel='external nofollow' to outgoing links. |
| 7 | +# - Automatically make headers linkable |
| 8 | +# |
| 9 | +require 'jekyll' |
| 10 | +require 'nokogiri' |
| 11 | + |
| 12 | +module Jekyll |
| 13 | + module OutputModder |
| 14 | + def output_modder(content) |
| 15 | + dom = Nokogiri::HTML.fragment(content) |
| 16 | + |
| 17 | + # Find all links, make all external links rel='external nofollow' |
| 18 | + dom.css('a').each do |link| |
| 19 | + rel = ['external', 'nofollow'] |
| 20 | + |
| 21 | + # All external links start with 'http', skip when this one does not |
| 22 | + next unless link.get_attribute('href') =~ /\Ahttp/i |
| 23 | + |
| 24 | + # Play nice with our own links |
| 25 | + next if link.get_attribute('href') =~ /\Ahttps?:\/\/\w*.?home-assistant.io/i |
| 26 | + |
| 27 | + # Play nice with links that already have a rel attribute set |
| 28 | + rel.unshift(link.get_attribute('rel')) |
| 29 | + |
| 30 | + # Add rel attribute to link |
| 31 | + link.set_attribute('rel', rel.join(' ').strip) |
| 32 | + end |
| 33 | + |
| 34 | + # Find all headers, make them linkable |
| 35 | + dom.css('h2,h3,h4,h5,h6,h7,h8').each do |header| |
| 36 | + |
| 37 | + # Skip linked headers |
| 38 | + next if header.at_css('a') |
| 39 | + |
| 40 | + title = header.content |
| 41 | + slug = title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '') |
| 42 | + header.children = "<a class='title-link' name='#{slug}' href='\##{slug}'></a> #{title}" |
| 43 | + end |
| 44 | + |
| 45 | + dom.to_s |
| 46 | + end |
| 47 | + end |
| 48 | +end |
| 49 | + |
| 50 | +Liquid::Template.register_filter(Jekyll::OutputModder) |
0 commit comments