Stop repeating your labels

I don’t know about you, but I do like a bit of form_for. I’m not so fond of having to repeat myself when writing labels though:

  <% form_for(:post, ...) do |f| %>
    <label for="post_title">Title</label>
    <%= f.text_field(:title) %>
    <label for="post_body">Body</label>
    <%= f.text_area(:body) %>
  <% end %>

You have to write the object name out every time, and the attribute name twice for every label. I’d rather do this:

  <% form_for(:post, ...) do |f| %>
    <%= f.label(:title) %>
    <%= f.text_field(:title) %>
    <%= f.label(:body) %>
    <%= f.text_area(:body) %>
  <% end %>

And now you can too:

script/plugin install
    http://svn.jcoglan.com/labelhelper/trunk/label_helper

LabelHelper takes the pain out of writing accessible, usable web forms. You can overwrite the default label text if you like, and add other tag options just like any other Rails tag method. The important thing is it deals with that pesky for attribute so you don’t have to. Enjoy.

I’ve asked for this to be added to Rails, as I figured it’s in keeping with its don’t-repeat-yourself philosophy. No idea how likely it is to be included though.

If you’ve enjoyed this article, you might enjoy my recently published book JavaScript Testing Recipes. It’s full of simple techniques for writing modular, maintainable JavaScript apps in the browser and on the server.