Class: Hpricot::Elem

Inherits:
Object show all
Defined in:
lib/haml/html.rb

Overview

See Also:

Instance Method Summary collapse

Instance Method Details

#to_haml(tabs, options) ⇒ Object



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/haml/html.rb', line 224

def to_haml(tabs, options)
  return "" if converted_to_haml
  if name == "script" &&
      (attributes['type'].nil? || attributes['type'] == "text/javascript") &&
      (attributes.keys - ['type']).empty?
    return script_to_haml(tabs, options)
  end

  output = tabulate(tabs)
  if options[:erb] && name[0...5] == 'haml:'
    case name[5..-1]
    when "loud"
      return output + "= #{CGI.unescapeHTML(inner_text).gsub(/\n\s*/, ' ').strip}\n"
    when "silent"
      return CGI.unescapeHTML(inner_text).split("\n").map do |line|
        next "" if line.strip.empty?
        "#{output}- #{line.strip}\n"
      end.join
    when "block"
      return render_children("", tabs, options)
    end
  end

  output << "%#{name}" unless name == 'div' &&
    (static_id?(options) ||
     static_classname?(options) &&
     attributes['class'].split(' ').any?(&method(:haml_css_attr?)))

  if attributes
    if static_id?(options)
      output << "##{attributes['id']}"
      remove_attribute('id')
    end
    if static_classname?(options)
      leftover = attributes['class'].split(' ').reject do |c|
        next unless haml_css_attr?(c)
        output << ".#{c}"
      end
      remove_attribute('class')
      set_attribute('class', leftover.join(' ')) unless leftover.empty?
    end
    output << haml_attributes(options) if attributes.length > 0
  end

  output << "/" if empty? && !etag

  if children && children.size == 1
    child = children.first
    if child.is_a?(::Hpricot::Text)
      if !child.to_s.include?("\n")
        text = child.to_haml(tabs + 1, options)
        return output + " " + text.lstrip unless text.chomp.include?("\n")
        return output + "\n" + text
      elsif ["pre", "textarea"].include?(name) ||
          (name == "code" && parent.is_a?(::Hpricot::Elem) && parent.name == "pre")
        return output + "\n#{tabulate(tabs + 1)}:preserve\n" +
          innerText.gsub(/^/, tabulate(tabs + 2))
      end
    elsif child.is_a?(::Hpricot::Elem) && child.name == "haml:loud"
      return output + child.to_haml(tabs + 1, options).lstrip
    end
  end

  render_children(output + "\n", tabs, options)
end