Rails3 get current layout name inside view

I have the answer for the Rails 2.X but not for Rails 3. How can I read the name of a current layout rendered inside a view.

My Rails2 question: http://stackoverflow.com/questions/2622219/rails-layout-name-inside-view

Thx.

-------------Problems Reply------------

Getting this to work in Rails 3.2 is a little more complicated than previously outlined. If your controller explicitly declares a layout, then the result of controller.send(:_layout) is a String, but otherwise it's an ActionView::Template. Try this:

module ApplicationHelper
def current_layout
layout = controller.send(:_layout)
if layout.instance_of? String
layout
else
File.basename(layout.identifier).split('.').first
end
end
end

I think it should be in core, but for now you can make a helper method:

def current_layout
controller.send :_layout
end

it will return currently used layout name

For Rails 4:

controller.send(:_layout)
=> 'application'

For Rails 3.2:

controller.send(:_layout)
=> #<ActionView::Template:0x000000082bb788>

But controller.send(:_layout).identifier returns the fullpath:

/home/davidm/Documentos/Devel/myapp/app/views/layouts/application.haml

You can do what I've done in my Ajax gem for Rails which is to wrap the _render_layout method:

ActionView::Base.class_eval do
def _render_layout_with_tracking(layout, locals, &block)
controller.instance_variable_set(:@_rendered_layout, layout)
_render_layout_without_tracking(layout, locals, &block)
end
alias_method_chain :_render_layout, :tracking
end

Then you can access the value that was set from your view (I'm pretty sure you have access to the controller there...) or in your controller in an after_filter, which is what I do.

I've written a custom RSpec 2 matcher which can be used to test layout rendering in Rails 3.

Category:layout Views:0 Time:2010-07-24

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.206 (s). 11 q(s)