Class: Html2haml::HTML

Inherits:
Object
  • Object
show all
Defined in:
lib/html2haml/html.rb,
lib/html2haml/html/erb.rb

Overview

Converts HTML documents into Haml templates. Depends on Nokogiri for HTML parsing. If ERB conversion is being used, also depends on Erubis to parse the ERB and ruby_parser to parse the Ruby code.

Example usage:

HTML.new("<a href='http://google.com'>Blat</a>").render
  #=> "%a{:href => 'http://google.com'} Blat"

Defined Under Namespace

Classes: ERB

Constant Summary collapse

TEXT_REGEXP =
/^(\s*).*$/

Instance Method Summary collapse

Constructor Details

#initialize(template, options = {}) ⇒ HTML

Returns a new instance of HTML.

Parameters:

  • template (String, Nokogiri::Node)

    The HTML template to convert

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :erb (Boolean) — default: false

    Whether or not to parse ERB's <%= %> and <% %> into Haml's = and -

  • :xhtml (Boolean) — default: false

    Whether or not to parse the HTML strictly as XHTML


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/html2haml/html.rb', line 132

def initialize(template, options = {})
  @options = options

  if template.is_a? Nokogiri::XML::Node
    @template = template
  else
    if template.is_a? IO
      template = template.read
    end

    template = Haml::Util.check_encoding(template) {|msg, line| raise Haml::Error.new(msg, line)}

    if @options[:erb]
      require 'html2haml/html/erb'
      template = ERB.compile(template)
    end

    @template = detect_proper_parser(template)
  end
end

Instance Method Details

#detect_proper_parser(template) ⇒ Object


153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/html2haml/html.rb', line 153

def detect_proper_parser(template)
  if template =~ /^\s*<!DOCTYPE|<html/i
    return Nokogiri.HTML(template)
  end

  if template =~ /^\s*<head|<body/i
    return Nokogiri.HTML(template).at('/html').children
  end

  parsed = Nokogiri::HTML::DocumentFragment.parse(template)

  #detect missplaced head or body tag
  #XML_HTML_STRUCURE_ERROR : 800
  if parsed.errors.any? {|e| e.code == 800 }
    return Nokogiri.HTML(template).at('/html').children
  end

  #in order to support CDATA in HTML (which is invalid) try using the XML parser
  # we can detect this when libxml returns error code XML_ERR_NAME_REQUIRED : 68
  if parsed.errors.any? {|e| e.code == 68 } || template =~ /CDATA/
    return Nokogiri::XML.fragment(template)
  end

  parsed
end

#renderObject Also known as: to_haml

Processes the document and returns the result as a string containing the Haml template.


181
182
183
# File 'lib/html2haml/html.rb', line 181

def render
  @template.to_haml(0, @options)
end