开发者

Confused on Advanced Rails Layout Nesting

I currently have a few layouts that my application uses (the ... is identical between all layouts):

# application.html.erb
...
<div id="section"><div class="wrapper"><%= yield %></div></div>
...

# wide.html.erb
...
<div id="section" class="wide"><div class="container-12"><%= yield %></div></div>
...

# thin.html.erb
...
<div id="section" class="thin"><div class="container-06"><%= yield %></div></div>
...

I am looking to re-factor t开发者_如何转开发he code to reduce duplication, however the strange placement of the class variables (outside the yield) makes it difficult. Should I be using variables for declaring the class values within my layout (and move to a single layout) or should I be adding container.html.erb layout that contains the duplicate ... then render the three other layouts from it (or does another third option exist that I am missing)? I'm looking for the "Rails" way to do it if possible. Thanks!


module ApplicationHelper
  def section_helper(outer_class=nil,inner_class)
    content_tag(:div, :class=> outer_class, :id => :section) do
      content_tag(:div, :class=> inner_class) do
        yield
      end
    end
  end
end

and in the layouts:

<%= section_helper("wrapper") { yield } %>
<%= section_helper("wide","container-12") { yield } %>
<%= section_helper("thin","container-06") { yield } %>

This works nicely for the first case where there is no "outer" class, since :class => nil renders nothing. But you could also pass in a hash if having an optional first argument is confusing.


We've done something like this using an instance variable like @sectionclass. Then we set it to a default in the ApplicationController and flip it to page specific values in other controllers. Then your page would be something like this:

<div id="section" class="<%= @sectionclass %>"><div class="container-12"><%= yield %></div></div>

The nice part of the instance variable is that the nil case fails silently with an empty string. (Albeit some may say this is 'bad').

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜