2011-02-11 33 views
5

我遇到的情況,我想有而我在佈局文件就是那個會被渲染視圖的名稱。我可以找到解決方案來查找哪個佈局將從視圖中包裝當前視圖,但不是相反。我怎樣才能找到哪個視圖正在呈現?Rails 3中,發現當前視圖,同時在佈局

回答

6

在Rails 3.0.3,我能看到的名字控制器和使用controller_name和action_name的操作。但那些沒有公開記錄(至少是行動名稱),所以我不會長期依賴它。

這可能是更好的猴子補丁模板渲染。在初始化程序中:

module ActionView::Rendering 
    alias_method :_render_template_original, :_render_template 
    def _render_template(template, layout = nil, options = {}) 
    @last_template = template 
    _render_template_original(template, layout, options) 
    end 
end 

然後在佈局中使用@last_template。

+0

這對我很好。要添加更多的細節,在Rails 3中添加此到一個新的文件配置/初始化/ custom_renderer.rb,然後在視圖中我能夠訪問@ last_template.variable_name得到的,例如,「新」 – 2011-08-27 15:35:36

0

我喜歡下面的方法,因爲可以減少代碼量好位在很多情況下。在application_controller.rb包括這樣的:

before_filter :instantiate_controller_and_action_names 
    caches_action :instantiate_controller_and_action_names 

    def instantiate_controller_and_action_names 
    @current_action = action_name 
    @current_controller = controller_name 
    end 

然後,如果你的觀點對應一個動作,你只是做:

dosomething if @current_action == 'new' 
+0

這並不完全解決我的問題。我需要視圖的名稱,它並不總是與被調用的動作相同。 – 2011-02-11 20:43:29

+0

然後,只需添加一個空白的動作,例如,無論結束。 – jschorr 2011-02-11 20:44:21

5

以下解決方案適用於Rails 3.1。將此代碼放入初始化程序中。 (導軌3.0.3答案在Rails 3.1中無法使用)

這使每個控制器都有一個@active_template變量。這是一個ActionViewTemplate類的實例。

的方法active_template_virtual_path方法返回的模板,如以下表格「控制器/行動」的名稱


    class ActionController::Base 
     attr_accessor :active_template 

     def active_template_virtual_path 
     self.active_template.virtual_path if self.active_template 
     end 
    end 

    class ActionView::TemplateRenderer 

     alias_method :_render_template_original, :render_template 

     def render_template(template, layout_name = nil, locals = {}) 

     @view.controller.active_template = template if @view.controller 
     result = _render_template_original(template, layout_name, locals) 
     @view.controller.active_template = nil if @view.controller 
     return result 

     end 
    end 
相關問題