gangelo
gangelo

Reputation: 3182

Obtain file name of the view associated with an action in the controller

I'm using rails 3.2. I want to be able to obtain the file name of the view that will be rendered by the action being executed in the controller. I want to get the last modified date of the file, but I am unsure how to dynamically get the file name of the view.

Upvotes: 2

Views: 381

Answers (2)

Valery Kvon
Valery Kvon

Reputation: 4496

Full path name of the current template in Rails 3:

Within View environment:

<%= @view_renderer.lookup_context.find_template(@virtual_path).identifier %>

Within controller actions:

# example

def index
  @template_path = lookup_context.find_template("#{controller_path}/#{action_name}").identifier
end

Upvotes: 3

Josh Rieken
Josh Rieken

Reputation: 2266

This is hard to do within the controller action and I'm not even sure it's possible since the controller action doesn't know which view will be rendered, if any, since a redirect is possible. But given you know the file extension of the view and assuming it's named the same as the action, you can do this:

Rails.root.join("app", "assets", "views", controller_name, action_name + ".html.erb").to_s

Within the view, you can do:

<%= __FILE__ %>

Upvotes: 1

Related Questions