在我的一个控制器中,我想在给定一些条件的情况下更改布局,否则保留父ApplicationController使用的默认布局(最初是"application",但我现在正在尝试其他一些)。尝试使用alias_method访问"布局",但似乎不起作用。我的代码:
class SomeController < ApplicationController
alias_method :parent_layout, :layout
layout :some_layout
def some_layout
if some_condition
"new_layout"
else
:parent_layout
end
end
end
这会产生一个错误:
ActionController::RoutingError (undefined method `layout' for class `SomeController'):
app/controllers/some_controller.rb:6:in `alias_method'
app/controllers/some_controller.rb:6:in `<class:SomeController>'
app/controllers/some_controller.rb:3:in `<top (required)>'
看起来有很多选项。查看此处的文档(搜索"查找布局")http://guides.rubyonrails.org/layouts_and_rendering.html
一些可能性,取决于你需要它的复杂程度:
# Proc-based
class ProductsController < ApplicationController
layout Proc.new { |controller| controller.request.xhr? ? "popup" : "application" }
end
# Route based, :except and :only
class ProductsController < ApplicationController
layout "product", except: [:index, :rss]
end
# Method-based
class OldArticlesController < SpecialArticlesController
layout false
def show
@article = Article.find(params[:id])
end
def index
@old_articles = Article.older
render layout: "old"
end
# ...
end
我不确定你的代码是如何构建的,但看起来第一个可能对你有用:
class SomeController < ApplicationController
layout Proc.new { |controller| controller.some_condition? ? "new_layout" : "application" }
end