简体   繁体   中英

Wrapping a Rails 3 block helper in another helper

I want to create a helper like this (I'm using the Formtastic gem):

def admin_form_for(record, columns = nil, &block)
  semantic_form_for [:admin, record] do |f|
    f.semantic_errors
    f.inputs *columns if columns
    capture(f, &block) if block_given?
    f.buttons
  end
end

I'm trying to wrap a block helper admin_form_for where we then call some methods that output text and then capture an ERB block in the middle of it.

I've tried all sorts of things

capture(f, &block) if block_given?

and

yield f if block_given?

and

concat(capture(f, &block)) if block_given?

nothing seems to work.

The usage of the helped ends up looking like this:

<%= admin_form_for @record, [:name, :email] do |f| %>
  <p><%= some_other_helper %></p>
<% end %>

I know this is a month late, but I think this is what you're looking for:

def admin_form_for(record, columns = nil, &block)
  with_output_buffer do  
    semantic_form_for [:admin, record] do |f|
      f.semantic_errors
      f.inputs *columns if columns
      capture(f, &block) if block_given?
      f.buttons
    end
  end
end

Here with_output_buffer returns a string representing the content rendered by the passed in block.

Sorry, didn't test it, but you can try this:

def admin_form_for(record, columns = nil, &block)
  semantic_form_for [:admin, record] do |f|
    f.semantic_errors
    f.inputs *columns if columns
    f.semantic_fields_for(columns, &block) if columns && block_given?
    f.buttons
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM