Sha256: 737b7cefd39b977b1f539c6faf76257a54b3a9f6ec12b32c051d4b4f7068b6de

Contents?: true

Size: 1.88 KB

Versions: 3

Compression:

Stored size: 1.88 KB

Contents

# Frozen-string-literal: true
# Copyright: 2012 - 2017 - MIT License
# Encoding: utf-8

require "pathutil"
require_relative "../utils"
require "jekyll/assets"
require "jekyll"

module Jekyll
  module Assets
    module Plugins
      # --
      # Searches for `<img>` that have `<img asset>` or
      # `<img asset="args">` and runs them through the asset
      # system.  This allows you to use real assets inside
      # of your Markdown pre-convert.
      # --
      class Searcher
        def initialize(doc)
          @doc = doc
        end

        # --
        def run
          html.search("img[@asset]").each do |v|
            raise ArgumentError, "src is empty" unless v[:src]
            args = "#{v.delete('src')&.value} #{v.delete('asset')&.value}"
            pctx = ::Liquid::ParseContext.new

            attrs = v.attributes.keys
            args, = Tag.new("asset", args, pctx).render_raw(ctx)
            args.to_h(html: true).each do |k, vv|
              unless attrs.include?(k.to_s)
                v.set_attribute(k, vv)
              end
            end
          end

          out = html.to_html
          @doc.output = out
        end

        # --
        private
        def ctx
          ::Liquid::Context.new({}, {}, {
            site: @doc.site,
          })
        end

        # --
        private
        def html
          @html ||= begin
            out = @doc.output
            # @see https://github.com/sparklemotion/nokogiri/issues/553
            good, buggy = Encoding::UTF_8, Encoding::ASCII_8BIT
            out = out.encode good if out.encoding == buggy
            Utils.send((@doc.output.strip =~ %r!<\!doctype\s+!i ? \
              :html : :html_fragment), out)
          end
        end
      end
    end
  end
end

Jekyll::Hooks.register [:pages, :documents, :posts], :post_render do |d|
  if d.output_ext == ".html"
    Jekyll::Assets::Plugins::Searcher.new(d).run
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
jekyll-assets-3.0.5 lib/jekyll/assets/plugins/searcher.rb
jekyll-assets-3.0.4 lib/jekyll/assets/plugins/searcher.rb
jekyll-assets-3.0.3 lib/jekyll/assets/plugins/searcher.rb