本文介绍了Ruby on Rails:在布局的特定位置产生特定视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个<%= yield %>标记,那么我所有的视图都将在布局中的同一位置呈现.我可以为不同的视图使用不同的<%= yield %>标签吗?是这样,我该怎么做?谢谢

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

推荐答案

查看 ActionView :: Helpers: :CaptureHelper .您可以在自己的视图中执行以下操作:

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

这将在content_for块中运行模板,但不会作为常规模板yield缓冲区的一部分输出,它将存储在单独的缓冲区中以备后用.之后,包括布局在内,您可以使用yield :content_name输出内容:

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>

从某种意义上说,对于不同的视图,您可以使用不同的yield,您只需要在视图中使用content_for为不同的内容命名,并在布局中使用相同的名称即可.

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.

考虑您的情况,在不同的地方需要不同的视图.假设您有三个面板,panel1,panel2和panel3.您可以在布局中执行此操作:

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>

如果您不想,甚至不需要添加普通的<%= yield %>.然后,在您的视图中,可以通过用适当的content_for包围整个视图来选择显示内容的面板.例如,您的其中一个视图可能会这样更改:

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

在面板2中显示.另一个可能用于面板3,如下所示:

To show in panel 2. Another one might be intended for panel 3, like this:

<% content_for :panel3 do %>
    <!-- Your View -->
<% end %>

这篇关于Ruby on Rails:在布局的特定位置产生特定视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 20:41