Is there a variable in Rails that equates to the template that is being rendered?
I can do request.path_parameters['controller'] and request.path_parameters['action'], but is ther开发者_开发技巧e anything like request.path_parameters['template'] so I can discern which template file (such as index.html.erb) is being rendered?
I'm writing a method that automatically sets the body id to the template being rendered, for easy css manipulation:
class ApplicationController < ActionController::Base
...
after_filter :define_body_selector
...
def define_body_selector
# sets @body_id to the name of the template that will be rendered
# ie. if users/index.html.erb was just rendered, @body_id gets set to "index"
@body_id = ???
end
...
If you have different template files you could use content_for
in them (check out guide about layouts and templates) to set id in layout file, or just stick to params[:action]
(it should be enough -- choice of template is based on action called).
You can make universal before_filter
for all (or not all) actions with
before_filter :set_id_for_body, :only => [...]
def set_id_for_body
@body_id = params[:action]
end
Always think how to keep your code DRY!
EDIT:
You could define hash that will link actions with matching templates:
ActionClasses = {
:update => "show",
:show => "show,
:new => "new",
:edit => "new",
...
}
Within your layout file just add
<body id="<%= ActionClasses[params[:action]] %>">
EDIT:
It is possible to access template via ActionBase::template
method, but it won't work the way you would like it to. If you call filename
or name
method in layout file, you will get path to layout file, not template. AFAIK It is impossible to check what template is being rendered, as multiple of them can be used to render single action.
@body_id = params[:action]
精彩评论