camerican / sinatra-formhelpers-ng

Lightweight, robust form helpers for Sinatra
Other
0 stars 0 forks source link

Add Ability to Turn Automatic Generation of IDs Off #1

Open camerican opened 8 years ago

camerican commented 8 years ago

Sometimes we don't want IDs polluting the DOM namespace. As of this writing, when we specify a form tag through the form helper, we automatically get both a name and id generated:

<%= label( :first_name, nil, "My First Name" ) %>
<%= input( :first_name ) %>

Will generate:

 <label for="first_name">My First Name</label>
 <input type="text" id="first_name" name="first_name">

We want to be able to suppress generation of the id attribute. Let's call the option that controls its generation id? which will be either true (default) or false:

<%= label( :first_name, nil, "My First Name" ) %>
<%= input( :first_name, nil, {id?: false} ) %>

Would generate:

 <label for="first_name">My First Name</label>
 <input type="text" name="first_name">
camerican commented 8 years ago

To get this behavior, created a new helper function options_preprocess which will set options[:ids] to true by default:

def options_preprocess(options)
  options[:id?] = true if options[:id?].nil? # set id? to true by default
  options
end

We just call this function from the end of the line tag and single_tag methods since the other form_helper functions eventually call this. The options are merged into the attributes parameter by the time they hit the tag function... we want to strip out :id if options[:id?] is not true and then strip out :id? also since it should not manifest within the tag.

def tag(name, content, attributes={})
  attributes.reject!{|k,v| k==:id } unless options_preprocess( attributes )[:id?]
  attributes.reject!{|k,v| k==:id?}
  unless content.nil?
    "<#{name.to_s} #{hash_to_html_attrs(attributes)}>#{content}</#{name.to_s}>"
  else
    "<#{name.to_s} #{hash_to_html_attrs(attributes)}>"
  end
end