If I have one <%= yield %>
tag then all my views render in the same place in the lay开发者_开发问答out. Can I have different <%= yield %>
tags for different views? Is so how do I do this? Thanks
Look into ActionView::Helpers::CaptureHelper. You can do something like this in your views:
<% content_for :sidebar do %>
<!-- sidebar content specific to this page -->
<% end %>
This will run the template inside the content_for block, but will not output as part of the regular template yield
buffer, it will be stored in a separate buffer for later. Then later on, including in the layout, you can use yield :content_name
to output the content:
<div class="content">
<%= yield %>
</div>
<div class="sidebar">
<%= yield :sidebar %>
</div>
So in a sense you can have different yield
s for different views, you just have to give the differing content a name with content_for
in the views, and yield it with that same name in the layout.
Consider your case, where you want different views in different places. Let's say you have three panels, panel1, panel2, and panel3. You can do this in your layout:
<div id="panel1"><%= yield :panel1 %></div>
<div id="panel2"><%= yield :panel2 %></div>
<div id="panel3"><%= yield :panel3 %></div>
You don't even need to include a plain <%= yield %>
if you don't want to. Then in your views, you can choose which panel to display the content in by surrounding the entire view with the appropriate content_for
. For example, one of your views might be changed like this:
<% content_for :panel2 do %>
<!-- Your View -->
<% end %>
To show in panel 2. Another one might be intended for panel 3, like this:
<% content_for :panel3 do %>
<!-- Your View -->
<% end %>
Yes, you can have multiple <%= yield %>
tags. You can specify each yield
tag with names like these in the base view.
<%= yield :head %>
<%= yield :footer %>
Then use the content_for
tag in your individual views.
<% content_for :head do %>
<%= stylesheet_link_tag 'custom' %>
<% end %>
You can use yield and content for:
For example:
<%= yield :head %>
<% content_for :head do %>
<title>A simple page</title>
<% end %>
- Refer :layout and rendering guide.
精彩评论