【问题标题】:Two-part Rails layouts两部分 Rails 布局
【发布时间】:2011-01-09 02:17:44
【问题描述】:

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

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

不确定这是最好的方法。

【问题讨论】:

    标签: ruby-on-rails layout partials


    【解决方案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 %>
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 抱歉,一开始没有正确阅读您的问题。编辑了我的答案,以便它与您的问题更相关。
      • 我喜欢你的方法——会试一试。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      相关资源
      最近更新 更多