简体   繁体   中英

How can you auto-generate placeholder text based on the field name in Rails?

I have a reusable field template, called _field.html.haml, that looks like (in haml):

= f.label field
= f.send(field_type, field, :class => field_type)

The advantage of this is that it can be called from a parent form template and provides reusability. This lets me dynamically render form fields based on a field type. The calling template looks like:

= form_for(@model) do |f|
  = render :partial => 'field', :locals => { :field => :first_name, :field_type => :text_field }
  = render :partial => 'field', :locals => { :field => :last_name, :field_type => :text_field }

How could I add auto-generating of the placeholder text based on the label text to this _field.html.haml template? Maybe the correct question is what is the code that the label hdlper uses to convert the field name to an capitalized english phrase?

Ie code would look like:

= f.send(field_type, field, :class => field_type, :placeholder => #INSERT CODE HERE to get friendly placeholder text)

the label_tag method uses `String#humanize" to make it look nicer (http://api.rubyonrails.org/classes/String.html#method-i-humanize). So in your example you could do:

= f.send(field_type, field, :class => field_type, :placeholder => field.to_s.humanize)

As previously mentioned in the comments, you should have a look at available form-builders. They abstract a lot of pain associated with making nice forms. Some links are:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM