Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - Multiple yield blocks on a partial

Is it possible to have a partial using more than one yield block? I wanted to use it to implement bootstrap modal boxes on my project, kinda like this:

<div class="modal fade" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <%= yield :header %>
            </div>

            <div class="modal-body">
                <%= yield :body %>
            </div>

            <div class="modal-footer">
                <%= yield :footer %>
            </div>
        </div>
    </div>
</div>

And this is more or less how I was thinking of using it

<%= render partial: "shared/modal" do %>
    <% content_for :header do %>
        ...        
    <% end %> %>

    <% content_for :body do %>
        ...        
    <% end %> %>

    <% content_for :footer do %>
        ...        
    <% end %> %>
<% end %>

Is there a way to do this? Is this maybe a bad approach for some reason?

like image 209
Enrique Moreno Tent Avatar asked Oct 27 '25 10:10

Enrique Moreno Tent


1 Answers

Through much trial and error, I think I solved this in Rails 5 but needed to insert a blank yield in my partial in order to get it to work:

_partial.html.erb

<div class="partial">
  <%= yield %> <!--Does not do anything-->
  <div class="header">
    <%= yield :header %>
  </div>
  <div class="text">
    <%= yield :text %>
  </div>
</div>

Implemented as:

full_layout.html.erb

<%= render "partial" do %>
  <% content_for :header do %>
    <h1>Header content</h1>
  <% end %>
  <% content_for :text do %>
    <p>Text content</p>
  <% end %>
<% end %>
like image 103
sambecker Avatar answered Oct 30 '25 01:10

sambecker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!