简体   繁体   中英

Ruby on Rails pass reference to yield (template)

To make long story short: each of my tabs has its own form, so I decided to make a single layout and just to have a forms themselves as a variable content for a layout.

But I need to have form_for to be in a layout, rather then having it in each of the forms, because I have some other common form elements in the layout.

So how can I pass the form builder's reference f to the template ?

Layout code:

<% content_for(:content) do %>
  <%= form_for current_form do |f| %>
    <%= yield %>
    <%= f.submit "Submit" %>
  <% end %>
<% end %>

Is it possible ?

PS Found this one: DRYing up a helper: wrap form_for and access local form variable (@rubish's answer), but <%= yield f %> doesn't seem to be working, f still remains undefined for the view.

Why don't you make a common template ( not layout) for the tabs, and use a partial template for the content of each tab?

Then you can do something like:

<%= render :partial => @tab_name, :locals => {:form => f} %>

You can render a template in Rails 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

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