I want to use the f.label method to create my form element labels, however - i want to have the form element nested inside the label. Is this possible?
-- From W3C --
You can use a custom FormBuilder to allow the label helper to accept a block. It's as simple as this:
class SmartLabelFormBuilder < ActionView::Helpers::FormBuilder
def label(method, content_or_options_with_block = nil, options = {}, &block)
if !block_given?
super(method, content_or_options_with_block, options)
else
options = content_or_options_with_block.is_a?(Hash) ? content_or_options_with_block.stringify_keys : {}
@template.content_tag(:label, options, &block)
end
end
end
Then you can use your form builder like this:
<% form_for(@article, :builder => SmartLabelFormBuilder) do |form| %>
<% form.label(:title) do %>
Title
<%= form.text_field(:title) %>
<% end %>
<% end %>