3

I want to enclose my text fields and other form elements in a label tag:

<label for="answer">Give it to me: <input type="text" id="answer" name="answer"/></label>

This way I can have the following CSS:

label {
   white-space: nowrap;
}

And then the label and form element never split onto separate lines. I know I can surround the whole label and form element with a <span> and use white-space: nowrap; on that, but I like having a label that covers everything. At least sometimes.

Question is how to do this in Rails using their label_tag form helper. Should I just include the other form element in the label_tag call?

<%= label_tag 'answer', "Give it to me: #{text_field_tag 'answer', @prev_answer, placeholder: 'Enter answer', class: 'special'}" %>
at.
  • 50,922
  • 104
  • 292
  • 461
  • Just a note, SimpleForm is a really good gem for forms, it handles most of this already and provides easy config to customize it further. – iouri Sep 21 '12 at 17:18

1 Answers1

3

You can use the block syntax of label_tag. Something like this:

<%= label_tag 'answer' do %>
  Give it to me: <%= text_field_tag 'answer', @prev_answer %>
<% end %>

More info:
http://openmonkey.com/blog/2010/03/30/rails-label-helpers-with-blocks/
Passing block to label helper in rails3

Community
  • 1
  • 1
MurifoX
  • 14,991
  • 3
  • 36
  • 60
  • The above didn't exactly work, the string you give `label_tag` is the `id` and you have to put the actual label between the `<% label_tag 'id' do %>` and `<%end%>`. – at. Sep 21 '12 at 19:53