Module: Haml::Compiler

Defined in:
lib/haml2handlebars/engine.rb

Class Method Summary collapse

Class Method Details

.build_attributes(is_html, attr_wrapper, escape_attrs, attributes = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/haml2handlebars/engine.rb', line 12

def self.build_attributes(is_html, attr_wrapper, escape_attrs, attributes = {})
  quote_escape = attr_wrapper == '"' ? """ : "'"
  other_quote_char = attr_wrapper == '"' ? "'" : '"'

  if attributes['data'].is_a?(Hash)
    attributes = attributes.dup
    attributes =
      Haml::Util.map_keys(attributes.delete('data')) {|name| "data-#{name}"}.merge(attributes)
  end

  result = attributes.collect do |attr, value|
    next if value.nil?

    value = filter_and_join(value, ' ') if attr == 'class'
    value = filter_and_join(value, '_') if attr == 'id'

    if value == true
      next " #{attr}" if is_html
      next " #{attr}=#{attr_wrapper}#{attr}#{attr_wrapper}"
    elsif value == false
      next
    end

    escaped =
      if escape_attrs == :once
        Haml::Helpers.escape_once(value.to_s)
      elsif escape_attrs
        Haml::Helpers.html_escape(value.to_s)
      else
        value.to_s
      end
    value = Haml::Helpers.preserve(escaped)
    if escape_attrs
      # We want to decide whether or not to escape quotes
      value = value.gsub('"', '"')
      this_attr_wrapper = attr_wrapper
      if value.include? attr_wrapper
        if value.include? other_quote_char
          value = value.gsub(attr_wrapper, quote_escape)
        else
          this_attr_wrapper = other_quote_char
        end
      end
    else
      this_attr_wrapper = attr_wrapper
    end

    if attr =~ /^hb-/
      attr = attr[3..-1]
      " {{#{attr} #{value}}}"
    else
      " #{attr}=#{this_attr_wrapper}#{value}#{this_attr_wrapper}"
    end
  end
  result.compact.sort.join
end