5

我的网页由两部分组成,比如说顶部和底部(页眉和页脚除外——它们在页面之间是一致的)。根据操作动态生成这些部分的最佳实践是什么?

我想出的一种方法是对顶部有视图,对底部有部分视图;在布局调用中,顶部为 yield ,底部为部分渲染。部分的名称根据动作动态替换。

不确定这是最好的方法。

4

2 回答 2

8

我觉得你的想法很好。在您看来,您可以这样做:

<%- content_for :top do -%>
  […]
<%- end -%>

<%- content_for :bottom do -%>
  <%= render @partial_name %>
<%- end -%>

当然,您应该检查部分是否存在并提供一些默认行为。但我想你无论如何都知道这一点。

然后在您的布局中:

<div id="top">
  <%= yield :top %>
</div>

<div id="bottom">
  <%= yield :bottom %>
</div>
于 2010-01-25T13:10:08.970 回答
1

这是我过去使用的视图 DSL 的一个非常简化的版本。为我们工作得很好。实际上,我们参数化了辅助方法,因此我们可以动态地从许多布局部分中进行选择(让页面具有侧边栏、多列等)。

# app/views/shared/_screen.erb
<div id="screen">
  <div class="screen_header">
 <%= yield :screen_header %>
  </div>
  <div class="screen_body">
 <%= yield :screen_body
  </div>
  <div class="bottom">
    <%= yield :footer %>
  </div>
</div>

# app/helpers/screen_helper.rb
module ScreenHelper

 def screen(&block)
  yield block
  concat(render :partial => 'shared/screen')
 end

 def screen_header
   content_for :screen_header do
   yield
  end
 end

 def screen_body
  content_for :screen_body do
   yield
  end
 end

 def footer
  content_for :footer do
   yield
  end
 end
end

# app/views/layouts/application.erb
# only showing the body tag
<body>
  <%= yield :layout
<body>

# Example of a page
# any of the sections below (except screen) may be used or omitted as needed.
# app/views/users/index.html.erb
<% screen do %>
  <% screen_header do %>
  Add all html and/or partial renders for the header here.
  <%end%>
  <% screen_body do %>
    Add all html and/or partial renders for the main content here.
  <% end %>
  <% footer do %>
 Add all the html and/or partial renders for the footer content here.
  <% end %>
<% end %>
于 2010-01-25T15:51:03.757 回答