Rails: render a template that accepts a block by using the layout option of render

Let's say you have a form that you render a few times but you would like to customize your submit section each time. You can achieve this by rendering your form partial as layout and passing in a block. Your template or partial then serves as the surrounding layout of the block that you pass in. You can then yield back the form to the block and access the form in your block.

record/_form.haml

= form_for record do |form|
  ...
  .form-actions
    yield(form)
  

In order to make your template record/_form.haml accept a block when you render it, you can render your template as the layout for your block using the layout option of render:

record/edit.haml

= render layout: 'form', locals: { record: record, ... } do |form|
  .form-actions--primary
    = form.button :submit
 
Andreas Robecke Over 6 years ago