diff --git a/_plugins/auto-link.rb b/_plugins/auto-link.rb index a2d4e867..9ef88772 100644 --- a/_plugins/auto-link.rb +++ b/_plugins/auto-link.rb @@ -1,8 +1,8 @@ require "nokogiri" require "addressable/uri" -Jekyll::Hooks.register [:pages, :documents], :post_convert do |doc| - next unless doc.output_ext == ".html" +def auto_link(doc) + return unless doc.output_ext == ".html" site = doc.site liquid_context = Liquid::Context.new({}, {}, { site: site }) diff --git a/_plugins/auto-webp.rb b/_plugins/auto-webp.rb new file mode 100644 index 00000000..e2f02a6c --- /dev/null +++ b/_plugins/auto-webp.rb @@ -0,0 +1,28 @@ +require "nokogiri" +require "addressable/uri" + +def auto_webp(doc) + return unless doc.output_ext == ".html" + + site = doc.site + liquid_context = Liquid::Context.new({}, {}, { site: site }) + + fragment = Nokogiri::HTML::DocumentFragment.parse(doc.content) + fragment.css("img[src^=\"/assets/\"]").each do |item| + next unless item["src"] + uri = Addressable::URI.parse(item["src"]) + next if uri.nil? + + source_path = uri.path + webp_path = "#{source_path}.webp" + begin + uri.path = Liquid::Template.parse("{% link #{source_path[1..]} %}").render!(liquid_context) + item["src"] = uri.to_s + uri.path = Liquid::Template.parse("{% link #{webp_path[1..]} %}").render!(liquid_context) + item.wrap("") + rescue => e + # Ignored + end + end + doc.content = fragment.to_html +end diff --git a/_plugins/hook.rb b/_plugins/hook.rb new file mode 100644 index 00000000..c188237f --- /dev/null +++ b/_plugins/hook.rb @@ -0,0 +1,7 @@ +require_relative "auto-link" +require_relative "auto-webp" + +Jekyll::Hooks.register [:pages, :documents], :post_convert do |doc| + auto_webp(doc) + auto_link(doc) +end