class Html2haml::HTML
Converts HTML documents into Haml templates. Depends on [Nokogiri](nokogiri.org/) for HTML parsing. If ERB conversion is being used, also depends on [Erubis](www.kuwata-lab.com/erubis) to parse the ERB and [ruby_parser](parsetree.rubyforge.org/) to parse the Ruby code.
Example usage:
HTML.new("<a href='http://google.com'>Blat</a>").render #=> "%a{:href => 'http://google.com'} Blat"
Constants
- TEXT_REGEXP
Public Class Methods
new(template, options = {})
click to toggle source
@param template [String, Nokogiri::Node] The HTML template to convert @option options :erb [Boolean] (false) Whether or not to parse
ERB's `<%= %>` and `<% %>` into Haml's `=` and `-`
@option options :xhtml [Boolean] (false) Whether or not to parse
the HTML strictly as XHTML
# 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
Public Instance Methods
detect_proper_parser(template)
click to toggle source
# 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
render()
click to toggle source
Processes the document and returns the result as a string containing the Haml template.
# File lib/html2haml/html.rb, line 181 def render @template.to_haml(0, @options) end
Also aliased as: to_haml