Skip to content

Instantly share code, notes, and snippets.

@uwabami
Created February 1, 2020 01:18
Show Gist options
  • Select an option

  • Save uwabami/8db4f20052fac4806005bb61e0b38377 to your computer and use it in GitHub Desktop.

Select an option

Save uwabami/8db4f20052fac4806005bb61e0b38377 to your computer and use it in GitHub Desktop.
jekyll で <img> を <amp-img> に変換する liquid filter. {{ content | amp_images }} とでもすると良い.
#
#= Jekyll Plugin: replace '<img>' to '<amp-img>' with fallback, noscript
#
# Original: https://github.com/juusaw/amp-jekyll/lib/jekyll/amp_filter.rb
# License: MIT/X11
# Note:
# - You have to set <img> with width and height
# - You have to add .png and .webp
require 'nokogiri'
module Jekyll
module AmpFilter
def amp_images(input, responsive = true, wi = nil, he = nil)
doc = Nokogiri::HTML.fragment(input);
# * Change 'img' elements to 'amp-img'
# * Add responsive attribute
doc.css('img').each do |image|
image.name = "amp-img"
image['layout'] = "responsive"
end
# NOTE: Rouge syntax highlihter use <figure></figure>.
doc.css('figure').each do |figure|
amp_img = figure.css('amp-img')
unless figure.css('amp-img').empty?
figure.add_next_sibling(amp_img)
figure.remove
end
end
# Added <img /> tag wrapped with <noscript /> in case js is not enabled
# but image will still show up. The element would look like this:
# <amp-img ...> <-- .webp
# <amp-img ... fallback></amp-img> <-- .png
# <noscript>
# <img ... />
# </noscript>
# </ampimg ...>
# Duplicate amp-img, remove layout attribut, wrap it with noscript, and add
# it as amp-img child
doc.css('amp-img').each do |amp_img|
noscript = Nokogiri::XML::Node.new "noscript", doc
noscript_img = amp_img.dup
fallback = amp_img.dup
fallback.set_attribute('fallback','dummy')
noscript_img.name = 'img'
src = noscript_img.attributes['src'].value
noscript_img.attributes['src'].value = src.gsub('.webp','.png')
fallback.attributes['src'].value = src.gsub('.webp','.png')
noscript_img.remove_attribute('layout')
noscript.add_child(noscript_img)
amp_img.add_child(fallback)
amp_img.add_child(noscript)
end
# ad hoc: return the html as plaintext string
doc.to_s.gsub(/fallback="dummy"/,'fallback')
end
end
end
Liquid::Template.register_filter(Jekyll::AmpFilter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment