Ruby on rails: Yielding specific views in a specif

2019-02-02 18:44发布

If I have one <%= yield %> tag then all my views render in the same place in the layout. Can I have different <%= yield %> tags for different views? Is so how do I do this? Thanks

3条回答
太酷不给撩
2楼-- · 2019-02-02 19:20

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 %>
查看更多
Luminary・发光体
3楼-- · 2019-02-02 19:23

You can use yield and content for:

 For example:
 <%= yield :head %>
<% content_for :head do %>
  <title>A simple page</title>
<% end %>
查看更多
时光不老,我们不散
4楼-- · 2019-02-02 19:33

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 yields 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 %>
查看更多
登录 后发表回答