views:

32

answers:

2

I can do request.path_parameters['controller'] and request.path_parameters['action'], but is there 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
  ...
A: 
@body_id = params[:action]
Salil
the problem is that while sometimes the "show" action renders the "show" page, sometimes the "update" action renders the "show" page as well. I need a way to distinctly set the <body id=???> to the name of the template being rendered (regardless of the action).
Sean Ahrens
A: 

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.

samuil
thanks, samuil. but params[:action] doesn't work well because while sometimes the "show" action renders the "show" page, sometimes the "update" action renders the "show" page as well. I need a way to distinctly set the <body id=???> to the name of the template being rendered (regardless of the action)."content_for" is a workaround that would enable me to set the body id explicitly in each template file, but requires very repetitive insertions of that line in every template file I create.
Sean Ahrens