tag_helper.rb 1.2 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1
require 'cgi'
2
require 'erb'
D
Initial  
David Heinemeier Hansson 已提交
3 4 5 6 7 8 9

module ActionView
  module Helpers
    # This is poor man's Builder for the rare cases where you need to programmatically make tags but can't use Builder.
    module TagHelper
      include ERB::Util

10
      # Examples:
D
David Heinemeier Hansson 已提交
11 12
      # * <tt>tag("br") => <br /></tt>
      # * <tt>tag("input", { "type" => "text"}) => <input type="text" /></tt>
13 14
      def tag(name, options = nil, open = false)
        "<#{name}#{tag_options(options.stringify_keys) if options}" + (open ? ">" : " />")
D
Initial  
David Heinemeier Hansson 已提交
15
      end
16 17

      # Examples:
D
David Heinemeier Hansson 已提交
18 19 20
      # * <tt>content_tag("p", "Hello world!") => <p>Hello world!</p></tt>
      # * <tt>content_tag("div", content_tag("p", "Hello world!"), "class" => "strong") => </tt>
      #   <tt><div class="strong"><p>Hello world!</p></div></tt>
21 22
      def content_tag(name, content, options = nil)
        "<#{name}#{tag_options(options.stringify_keys) if options}>#{content}</#{name}>"
D
Initial  
David Heinemeier Hansson 已提交
23 24 25 26
      end

      private
        def tag_options(options)
27 28 29 30
          if options
            options.inject("") do |html_str, (key, value)|
              value.nil? ? html_str : html_str << %( #{key}="#{html_escape(value)}")
            end
D
Initial  
David Heinemeier Hansson 已提交
31 32 33 34
          end
        end
    end
  end
35
end