这是我正在尝试做的一些模型代码:
class ApplicationController < ActionController::Base
layout "application"
end
class SomeController < ActionController::Base
verify :method => :get, :only => [:index]
def index
@some_objects = Some.collect
end
end
# Now in: views/some/index.html.erb
<% if @some_objects %>
# use the application layout
<%= render(:partial => 'some/objects', :locals => {:some_objects => @some_objects}) %>
<% else %>
# use a different layout than application
# some/sales_page --> views/some/_sales_page.html.erb
# layouts/sales --> views/layouts/sales.html.erb
<%= render('some/sales_page', :layout => 'layouts/sales') %>
<% end %>
正如您所看到的,我正在尝试为部分some / sales_page呈现与应用程序不同的布局。我该怎么办?
注意:我的Rails版本是2.3.11。
答案 0 :(得分:1)
这非常简单,render
方法采用:layout
选项(基本上就是你的示例),但是你的布局可以和调用文件存在于同一个目录中并使用它部分命名约定(即以下划线开头)。因此,对于您的示例,如果将是以下几行:
#In: views/some/index.html.erb
<% if @some_objects %>
# use the application layout
<%= render(:partial => 'objects', :locals => {:some_objects => @some_objects}) %>
<% else %>
<%= render(:partial => 'sales_page', :layout => 'sales_layout') %>
<% end %>
views/some
文件夹的内容如下:
views/some/index.html.erb
views/some/_objects.html.erb
views/some/_sales_page.html.erb
views/some/_sales_layout.html.erb
答案 1 :(得分:-1)
您只能在控制器层中更改布局。
class SomeController < ActionController::Base
layout :choose_layout
verify :method => :get, :only => [:index]
def index
@some_objects = Some.collect
end
private
def choose_layout
@some_objects = Some.collect
@some_objects ? "application" : "different_layout"
end
end