Read more

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

Andreas Robecke
September 01, 2017Software engineer

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)
  
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

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
 
Posted by Andreas Robecke to makandra dev (2017-09-01 14:24)