Rails 3,在布局中找到当前视图

我有一个场景,我希望在布局文件中有渲染视图的名称。 我可以找到解决方案来查找哪个布局将从视图中包装当前视图,但不是相反。 如何找到正在渲染的视图?

在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。

以下解决方案适用于Rails 3.1。 将此代码放在初始化程序中。 (Rails 3.1中的rails 3.0.3答案不再起作用了)

这为每个控制器启用了@active_template变量。 这是ActionViewTemplate类的一个实例。

方法active_template_virtual_path方法以下面的forms“控制器/操作”返回模板作为名称

 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 

我喜欢以下方法,因为在很多情况下你可以减少代码大小。 将其包含在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'