5

私のWebページは、たとえば上部と下部の2つの部分で構成されています(ヘッダーとフッターを除く-これらはページ間で一貫しています)。アクションに応じてこれらのパーツを動的に生成するためのベストプラクティスは何ですか?

私が思いついたアプローチの1つは、上部を表示し、下部を部分的に表示することです。レイアウトでは、上部の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 に答える