module Form class Tag # List which tags don't need to be closed. # Did you know that the technical name is "void elements"? # http://www.w3.org/TR/html5/syntax.html#void-elements # VOID_ELEMENTS = [ :area, :base, :br, :col, :command, :embed, :hr, :img, :input, :keygen, :link, :meta, :param, :source, :track, :wbr ] # The tag name. # attr_accessor :name # The tag content. It will be ignored in open tags. # attr_accessor :content # The tag attributes. # attr_accessor :attributes # Escape the value. # def self.html_escape(string) string.to_s.gsub(/&/, "&").gsub(/\"/, """).gsub(/>/, ">").gsub(/

Hello World!

# def initialize(name, content = "", attributes = {}, &block) if content.kind_of?(Hash) attributes = content content = "" end @name = name.to_sym @content = content @attributes = attributes yield self if block_given? end # Detect if this tag omits the closing part. # def void? VOID_ELEMENTS.include?(name) end # Append the specified HTML to this tag. # def <<(element) @content << element.to_s end # Create nested tags with ease. # def tag(name, content = "", attributes = {}, &block) @content << self.class.new(name, content, attributes, &block).to_s end # Build the tag, concating all parts. # def to_s open_tag << (void? ? "" : content.to_s) << close_tag end def html_escape(string) self.class.html_escape(string) end private # # def render_attributes attributes.collect do |name, value| next unless value && value != "" bool?(value) ? " #{name}" : %[ #{name}="#{html_escape(value)}"] end.join("") end # Check if value is boolean. # LolRuby doesn't have a Boolean class or something. # def bool?(value) value.kind_of?(TrueClass) || value.kind_of?(FalseClass) end # The opening part of the tag. # def open_tag "<#{name}#{render_attributes}>" end # The closing part of the tag. # def close_tag void? ? "" : "" end end end