rails 3,如何添加一个不使用相同布局的视图作为应用程序的其余部分?

jpw*_*ynn 51 layout ruby-on-rails

我找不到任何关于如何构建我的应用程序的文档或示例,以允许同一控制器中的不同视图使用完全不同的布局和样式表.

我们的应用程序是脚手架,然后我们使用漂亮的生成器生成视图,然后添加设计用于身份验证.我们有两个模型的视图和控制器:小部件和公司.

我目前只有一个布局:layouts/application.html.haml,我没有看到任何地方引用,所以我假设(一个新手),它总是被命名约定使用.

我现在需要在相同的控制器中添加一些视图(对于移动浏览器),这些视图具有不同的样式表和布局(例如,右上角没有登录/注销链接).

怎么办?

Pet*_*ong 129

默认情况下,layouts/application.html.haml(.erb如果你没有使用haml).

实际上,可以为每个控制器或每个操作设置布局文件,而不是每个视图文件夹的每个视图.

几个案例:

更改所有控制器的默认布局文件(即使用another.html.haml而不是application.html.haml)

class ApplicationController < ActionController::Base
  layout "another"

  # another way
  layout :another_by_method
  private
  def another_by_method
    if current_user.nil?
      "normal_layout"
    else
      "member_layout"
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

更改某个控制器中的所有操作以使用其他布局文件

class SessionsController < ActionController::Base
  layout "sessions_layout"
  # similar to the case in application controller, you could assign a method instead
end
Run Code Online (Sandbox Code Playgroud)

要更改操作以使用其他布局文件

def my_action
  if current_user.nil?
    render :layout => "normal_layout"
  else
    render :action => "could_like_this", :layout => "member_layout"
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 使用最后一种操作方法,我正确地处理了布局渲染问题.我将它添加到控制器`layout"cust_layout"的顶部,:only => [:my_action]`来解决问题.我还在操作中删除了`render:layout =>"normal_layout"`并将其替换为`format.html`.为条件布局引用此链接 - [Rails条件布局](http://guides.heroku.com/2.3.5/layouts_and_rendering.html#conditional-layouts) (3认同)