Module: Srcset
- Defined in:
- lib/jekyll-srcset-hook.rb
Class Method Summary collapse
- .modify_page_output ⇒ Object
- .modify_post_output ⇒ Object
- .process_image(image, transformations, sizes) ⇒ Object
- .set_config ⇒ Object
Class Method Details
.modify_page_output ⇒ Object
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 |
# File 'lib/jekyll-srcset-hook.rb', line 56 def modify_page_output proc do |page| doc = Nokogiri.HTML5(page.content) elements = doc.xpath(".//body//img") # for some reason, need to remove last element as it is empty elements.pop elements.each do |image| next unless image[:src].start_with?( @config["url_endpoint"] || @config["pages"]["url_endpoint"] ) original_image = image original_image = original_image.to_s.gsub!(">", " />") image = process_image( image, @config["transformations_widths"] || @config["pages"]["transformations_widths"], @config["sizes"] || @config["pages"]["sizes"] ) page.output.gsub!(original_image, image) end end end |
.modify_post_output ⇒ Object
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 |
# File 'lib/jekyll-srcset-hook.rb', line 29 def modify_post_output proc do |post| # posts are fragments (i.e. no DOCTYPE declaration/<html>...</html>) fragment = Nokogiri::HTML5.fragment(post.content) fragment .xpath(".//img") .each do |image| next unless image[:src].start_with?( @config["url_endpoint"] || @config["posts"]["url_endpoint"] ) original_image = image original_image = original_image.to_s.gsub!(">", " />") image = process_image( image, @config["transformations_widths"] || @config["posts"]["transformations_widths"], @config["sizes"] || @config["posts"]["sizes"] ) post.output.gsub!(original_image, image) end end end |
.process_image(image, transformations, sizes) ⇒ Object
84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/jekyll-srcset-hook.rb', line 84 def process_image(image, transformations, sizes) srcset_value = "" transformations.each do |t_w| srcset_value += "#{image[:src]}#{t_w}, " end # remove the extra ", " at the end of srcset_value srcset_value.chomp!(", ") # add the attributes to the image image[:srcset] = srcset_value image[:sizes] = sizes image.to_s.gsub!(">", " />") end |
.set_config ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/jekyll-srcset-hook.rb', line 8 def set_config proc do |site| @config = site.config["jekyll-srcset-hook"] if @config.nil? Jekyll.logger.warn( "WARNING: jekyll-srcset configuration is not present in _config.yml" ) next end unless @config["transformations_widths"].nil? && @config["sizes"].nil? Jekyll::Hooks.register(:posts, :post_render, &modify_post_output) Jekyll::Hooks.register(:pages, :post_render, &modify_page_output) end Jekyll::Hooks.register(:posts, :post_render, &modify_post_output) unless @config["posts"].nil? Jekyll::Hooks.register(:pages, :post_render, &modify_page_output) unless @config["pages"].nil? end end |