Nest input inside f.label ( rails form generation )

前端 未结 5 421
广开言路
广开言路 2020-12-28 17:22

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 --

5条回答
  •  隐瞒了意图╮
    2020-12-28 18:10

    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 %>
    

提交回复
热议问题