Ruby on rails: Yielding specific views in a specific places in the layout

蹲街弑〆低调 提交于 2019-11-29 01:29:29

问题


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


回答1:


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 %>



回答2:


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 %>



回答3:


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.


来源:https://stackoverflow.com/questions/7512486/ruby-on-rails-yielding-specific-views-in-a-specific-places-in-the-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!