How does the yield magic work in ActionView?

后端 未结 3 1578
名媛妹妹
名媛妹妹 2021-01-14 14:55

I was looking at how content_for works and observed the block.call in the capture_erb_with_buffer method. It apparently magically writes to the buf

3条回答
  •  囚心锁ツ
    2021-01-14 15:40

    I'm not certain how yield functions on the ERB level, but I do know how it works when applied to layouts.

    Heres a sample layout.html.erb file:

    
      
         <%= @title || 'Plain Title' %> 
        <%= yield :head %>
      
    
      
      
    <%= yield %>

    I have defined 4 yields(:head, :menu, :footer, and default) and an instance variable @title.

    Now controller actions can render views that slot into these spots. Note that the view renders before the layout, so I can define a variable like @title in a view and have it defined in the layout.

    Sample views: An About page

    <% @title = 'About' %>
    <% content_for :menu do %>
      <%= link_to 'Back to Home', :action => :home %>
    <% end %>
    
    We rock!
    
    <% content_for :footer do %>
      An Illinois based company.
    <% end %>
    

    An Edit page

    <% @title = 'Edit' %>
    <% content_for :head do %>
      
    <% end %>
    
    <% form_for :thing, :html => {:class => 'edit_form'} do |f| %>
       ...
    <% end %>
    

    You can mix and match what yields you want to put data in, and what occurs in the content_for :something will be inserted in the matching yield :something in the layout file.

    It even works for partials, a partial can insert its own content_for :something block which will get added with any other content_for calls.

提交回复
热议问题