10 3 / 2008

Rails Tip: Labels with form_for

If you use “form_for” you may have noticed in Rails 2.0 that there is now a label method to create html label tags: This is great for two reasons:

  1. It syncs the label tag’s “for” attribute with the “id” of whatever input field you create. This awesome for standards and accessibility!
  2. It will automatically create label text based off the method argument you pass in.

So instead of doing this:

  
<%- form_for @post do |f| -%>
  <div>
      <label for="post_title">Title</label>
      <%= f.text_field :title %>
  </div>
...
  

You can now do this! Which will take the method argument (:title) and create the label text (“Title”).


<%- form_for @post do |f| -%>
  <div>
      <%= f.label :title %>
      <%= f.text_field :title %>`
  </div>
...

Also, if you have label text that doesn’t quite match the method of your object or maybe you need the string to be translated in a different language. You can do this as well:

  
<%- form_for @post do |f| -%>
  <div>
    <%= f.label :title, _('Title') %>
    <%= f.text_field :title %>
  </div>
...