require 'nokogiri' module GalleryItems # Uploaded batches share one source document, but each photo is a gallery item. # Keeping this at render time also fixes batches that have already been published. def gallery_items(content) fragment = Nokogiri::HTML::DocumentFragment.parse(content) images = fragment.css('img') return [content] unless images.length > 1 && images.all? { |image| image['src'].to_s.start_with?('/img/arts/uploads/') && image.parent.name == 'p' } captions = fragment.css('.image-details').map(&:to_html).join images.each { |image| image.parent.remove } fragment.css('.image-details').each(&:remove) # Preserve the batch's existing anchor exactly once, before the first photo. prefix = fragment.to_html images.each_with_index.map do |image, index| "#{index.zero? ? prefix : ''}
#{image.to_html}
#{captions}" end end end Liquid::Template.register_filter(GalleryItems)