From b26f8d8146b82c327738cf8a1fdfaec41727ec9c Mon Sep 17 00:00:00 2001 From: neveler <55753029+neveler@users.noreply.github.com> Date: Thu, 20 Nov 2025 15:56:56 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=85=88=E4=BD=BF=E7=94=A8=20WebP=20?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E7=9A=84=E5=9B=BE=E7=89=87=EF=BC=88=E5=A6=82?= =?UTF-8?q?=E6=9E=9C=E5=8F=AF=E7=94=A8=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- _plugins/auto-link.rb | 4 ++-- _plugins/auto-webp.rb | 28 ++++++++++++++++++++++++++++ _plugins/hook.rb | 7 +++++++ 3 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 _plugins/auto-webp.rb create mode 100644 _plugins/hook.rb 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