Class: Slaw::Render::HTMLRenderer

Inherits:
Object
  • Object
show all
Defined in:
lib/slaw/render/html.rb

Overview

Support for transforming XML AN documents into HTML.

This rendering is done using XSLT stylesheets. Both an entire document and fragments can be rendered.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHTMLRenderer

Returns a new instance of HTMLRenderer.



13
14
15
16
17
18
19
20
# File 'lib/slaw/render/html.rb', line 13

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

Instance Attribute Details

#xsltObject

Hash

A Hash of Nokogiri::XSLT objects



11
12
13
# File 'lib/slaw/render/html.rb', line 11

def xslt
  @xslt
end

Instance Method Details

#_run_xslt(xslt, doc, params) ⇒ Object



61
62
63
# File 'lib/slaw/render/html.rb', line 61

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

#_transform_params(params) ⇒ Object



65
66
67
# File 'lib/slaw/render/html.rb', line 65

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

#render(doc, base_url = '') ⇒ String

Transform an entire XML document (a Nokogiri::XML::Document object) into HTML. Specify ‘base_url` to manage the base for relative URLs generated by the transform.

Parameters:

  • doc (Nokogiri::XML::Document)

    document to render

  • base_url (String) (defaults to: '')

    root URL for relative URLs (cannot be empty)

Returns:

  • (String)


30
31
32
33
# File 'lib/slaw/render/html.rb', line 30

def render(doc, base_url='')
  params = _transform_params({'base_url' => base_url})
  _run_xslt(:act, doc, params)
end

#render_node(node, base_url = '') ⇒ String

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.

Parameters:

  • node (Nokogiri::XML::Node)

    node to render

  • base_url (String) (defaults to: '')

    root URL for relative URLs (cannot be empty)

Returns:

  • (String)


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/slaw/render/html.rb', line 45

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