簡體   English   中英

如何訪問父控制器的“布局”?

[英]How to access 'layout' of parent controller?

在我的一個控制器中,我希望在給定某些條件的情況下更改布局,否則保持父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)>'

看起來你有很多選擇。 查看這里的文檔(搜索“查找布局”) 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM