0

在我的一个控制器中,我想在某些条件下更改布局,否则保留父 ApplicationController 使用的默认布局(最初是“应用程序”,但我现在正在尝试其他一些布局)。尝试使用 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)>'
4

1 回答 1

0

看起来你有很多选择。在此处查看文档(搜索“查找布局”) 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
于 2015-02-28T22:27:08.740 回答