at.
at.

Reputation: 52500

Including form elements in a label_tag in Rails

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'}" %>

Upvotes: 3

Views: 5404

Answers (1)

MurifoX
MurifoX

Reputation: 15089

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

Upvotes: 4

Related Questions