在Rails中为每个控制器正确呈现多个布局

pru*_*ett 8 layout render view ruby-on-rails-3.1

我在我的Users_controller中定义了:

layout "intro", only: [:new, :create]

这是我的布局: Intro.html.haml

!!! 5
%html{lang:"en"}
%head
  %title Intro
  = stylesheet_link_tag    "application", :media => "all"
  = javascript_include_tag "application"
  = csrf_meta_tags
%body{style:"margin: 0"}
  %header
    = yield
  %footer= debug(params)
Run Code Online (Sandbox Code Playgroud)

当我渲染一个要求intro作为布局的页面时,它嵌套在我的application.html.haml文件中,这是不好的.

有没有办法避免这种不受欢迎的布局嵌套?

提前致谢!

pru*_*ett 50

问题发生在我的控制器中.我正在声明多个布局实例,如下所示:

class UsersController < ApplicationController
  layout "intro", only: [:new, :create]
  layout "full_page", only: [:show]
  ...
end
Run Code Online (Sandbox Code Playgroud)

不要这样做! 第二个声明优先,你不会得到你想要的影响.

相反,如果您的布局只是特定于操作,只需在操作中声明它,如下所示:

def show
...
render layout: "full_page"
end
Run Code Online (Sandbox Code Playgroud)

或者,如果它有点复杂,您可以使用符号将处理延迟到运行时的方法,如下所示:

class UsersController < ApplicationController
  layout :determine_layout
  ...

  private
    def determine_layout
      @current_user.admin? ? "admin" : "normal"
    end
end
Run Code Online (Sandbox Code Playgroud)