Sha256: 0120035536337ac207dbca075e4c76e611729e5608375c55e16d6bbb35051717

Contents?: true

Size: 1.59 KB

Versions: 1

Compression:

Stored size: 1.59 KB

Contents

module Slaw
  module Render

    # Support for transforming XML AN documents into HTML.
    class HTMLRenderer
      def initialize
        here = File.dirname(__FILE__)

        @xslt = {
          act: Nokogiri::XSLT(File.open(File.join([here, 'xsl/act.xsl']))),
          fragment: Nokogiri::XSLT(File.open(File.join([here, 'xsl/fragment.xsl']))),
        }
      end

      # Transform an entire XML document +doc+ (a Nokogiri::XML::Document object) into HTML.
      # Specify +base_url+ to manage the base for relative URLs generated by
      # the transform.
      def render(doc, base_url='')
        params = transform_params({'base_url' => base_url})
        run_xslt(:act, doc, params)
      end

      # Transform just a single node and its children into HTML.
      #
      # If +elem+ has an id, we use xpath to tell the XSLT which
      # element to transform. Otherwise we copy the node into a new
      # tree and apply the XSLT to that.
      def render_node(node, base_url='')
        params = transform_params({'base_url' => base_url})

        if node.id
          params += ['root_elem', "//*[@id='#{node.id}']"]
          doc = node.document
        else
          # create a new document with just this element at the root
          doc = Nokogiri::XML::Document.new
          doc.root = node
          params += ['root_elem', '*']
        end

        run_xslt(:fragment, doc, params)
      end

      def run_xslt(xslt, doc, params)
        @xslt[xslt].transform(doc, params).to_s
      end

      def transform_params(params)
        Nokogiri::XSLT.quote_params(params)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
slaw-0.1.2 lib/slaw/render/html.rb