Rails 3,在布局中查找当前视图 [英] Rails 3, find current view while in the layout

查看:59
本文介绍了Rails 3,在布局中查找当前视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我希望拥有在布局文件中时将要渲染的视图的名称.我可以找到解决方案以从视图中找到将要包装当前视图的布局,而不是相反.如何找到正在渲染的视图?

I have a scenario where I would like to have the name of the view that will be rendering while I'm in the layout file. I can find solutions to find which layout will be wrapping the current view from the view, but not the other way around. How can I find which view is rendering?

推荐答案

在Rails 3.0.3中,我可以使用controller_name和action_name看到控制器和操作的名称.但是这些没有公开记录下来(至少是动作名称),所以我不会长期依赖它.

In Rails 3.0.3, I was able to see the name of the controller and action using controller_name and action_name. But those are not publicly documented (at least the action name) so I wouldn't depend on it long-term.

最好使用猴子补丁模板渲染.在初始化程序中:

It might be better to monkey patch template render. In an initializer:

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.

Then use @last_template in your layout.

这篇关于Rails 3,在布局中查找当前视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆