tag_helper.rb 5.5 KB
Newer Older
1
require 'active_support/core_ext/object/blank'
2
require 'set'
D
Initial  
David Heinemeier Hansson 已提交
3 4

module ActionView
R
Rizwan Reza 已提交
5
  # = Action View Tag Helpers
6
  module Helpers #:nodoc:
7
    # Provides methods to generate HTML tags programmatically when you can't use
8
    # a Builder. By default, they output XHTML compliant tags.
D
Initial  
David Heinemeier Hansson 已提交
9 10 11
    module TagHelper
      include ERB::Util

12 13 14
      extend ActiveSupport::Concern
      include CaptureHelper

15 16 17 18
      BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked autobuffer
                           autoplay controls loop selected hidden scoped async
                           defer reversed ismap seemless muted required
                           autofocus novalidate formnovalidate open).to_set
19
      BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attr| attr.to_sym })
20

21 22 23
      # Returns an empty HTML tag of type +name+ which by default is XHTML
      # compliant. Set +open+ to true to create an open tag compatible
      # with HTML 4.0 and below. Add HTML attributes by passing an attributes
24 25
      # hash to +options+. Set +escape+ to false to disable attribute value
      # escaping.
26 27
      #
      # ==== Options
28
      # The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and
29
      # <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use
30 31
      # symbols or strings for the attribute names.
      #
32
      # ==== Examples
33
      #   tag("br")
34 35
      #   # => <br />
      #
36
      #   tag("br", nil, true)
37 38
      #   # => <br>
      #
39
      #   tag("input", { :type => 'text', :disabled => true })
40 41
      #   # => <input type="text" disabled="disabled" />
      #
42 43 44 45 46 47
      #   tag("img", { :src => "open & shut.png" })
      #   # => <img src="open &amp; shut.png" />
      #
      #   tag("img", { :src => "open &amp; shut.png" }, false, false)
      #   # => <img src="open &amp; shut.png" />
      def tag(name, options = nil, open = false, escape = true)
48
        "<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
D
Initial  
David Heinemeier Hansson 已提交
49
      end
50

51
      # Returns an HTML block tag of type +name+ surrounding the +content+. Add
52
      # HTML attributes by passing an attributes hash to +options+.
53 54
      # Instead of passing the content as an argument, you can also use a block
      # in which case, you pass your +options+ as the second parameter.
55
      # Set escape to false to disable attribute value escaping.
56
      #
57
      # ==== Options
58
      # The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and
59 60 61 62
      # <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use
      # symbols or strings for the attribute names.
      #
      # ==== Examples
63 64 65 66 67 68
      #   content_tag(:p, "Hello world!")
      #    # => <p>Hello world!</p>
      #   content_tag(:div, content_tag(:p, "Hello world!"), :class => "strong")
      #    # => <div class="strong"><p>Hello world!</p></div>
      #   content_tag("select", options, :multiple => true)
      #    # => <select multiple="multiple">...options...</select>
69
      #
70
      #   <%= content_tag :div, :class => "strong" do -%>
71 72
      #     Hello world!
      #   <% end -%>
P
Pratik Naik 已提交
73
      #    # => <div class="strong">Hello world!</div>
74
      def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
75 76
        if block_given?
          options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
77
          content_tag_string(name, capture(&block), options, escape)
78
        else
79
          content_tag_string(name, content_or_options_with_block, options, escape)
80
        end
D
Initial  
David Heinemeier Hansson 已提交
81 82
      end

83
      # Returns a CDATA section with the given +content+.  CDATA sections
84 85
      # are used to escape blocks of text containing characters which would
      # otherwise be recognized as markup. CDATA sections begin with the string
86 87
      # <tt><![CDATA[</tt> and end with (and may not contain) the string <tt>]]></tt>.
      #
88
      # ==== Examples
89
      #   cdata_section("<hello world>")
90 91 92 93
      #   # => <![CDATA[<hello world>]]>
      #
      #   cdata_section(File.read("hello_world.txt"))
      #   # => <![CDATA[<hello from a text file]]>
94
      def cdata_section(content)
95
        "<![CDATA[#{content}]]>".html_safe
96 97
      end

98
      # Returns an escaped version of +html+ without affecting existing escaped entities.
99
      #
100
      # ==== Examples
P
Pratik Naik 已提交
101
      #   escape_once("1 < 2 &amp; 3")
102 103 104 105
      #   # => "1 &lt; 2 &amp; 3"
      #
      #   escape_once("&lt;&lt; Accept & Checkout")
      #   # => "&lt;&lt; Accept &amp; Checkout"
106
      def escape_once(html)
107
        ActiveSupport::Multibyte.clean(html.to_s).gsub(/[\"><]|&(?!([a-zA-Z]+|(#\d+));)/) { |special| ERB::Util::HTML_ESCAPE[special] }
108 109
      end

D
Initial  
David Heinemeier Hansson 已提交
110
      private
111

112 113
        def content_tag_string(name, content, options, escape = true)
          tag_options = tag_options(options, escape) if options
114
          "<#{name}#{tag_options}>#{escape ? ERB::Util.h(content) : content}</#{name}>".html_safe
115
        end
116

117
        def tag_options(options, escape = true)
118 119
          unless options.blank?
            attrs = []
120 121 122 123 124 125 126
            options.each_pair do |key, value|
              if BOOLEAN_ATTRIBUTES.include?(key)
                attrs << %(#{key}="#{key}") if value
              elsif !value.nil?
                final_value = value.is_a?(Array) ? value.join(" ") : value
                final_value = escape_once(final_value) if escape
                attrs << %(#{key}="#{final_value}")
127
              end
128
            end
129
            " #{attrs.sort * ' '}".html_safe unless attrs.empty?
130
          end
131
        end
D
Initial  
David Heinemeier Hansson 已提交
132 133
    end
  end
134
end