Oliver Morgan
Oliver Morgan

Reputation: 610

rails - Dynamically change view file name on render in

In my application I'm making heavy use of AJAX views. Like the user signup page is a AJAX-requested popup. However this approach isn't SEO friendly as google can't index "popups" and obviously you can't permalink a popup page.

So what I want to do is have a before_render like callback where I can dynamically append .xhr to my view name if the request is ajax based. It would be good to keep this DRY and not have to code this into every controller.

An example of how this would be done manually is:

def new
  render request.xhr? ? 'new.xhr' : 'new'
end

Any idea of how this can be achieved without re-writing every single one of my controllers?

Upvotes: 1

Views: 604

Answers (1)

Oliver Morgan
Oliver Morgan

Reputation: 610

Managed to find a solution to this. After tracing the render call I found the easiest way to achieve this was by adding the following to your ApplicationController

private

  def _process_options options
    options[:template] += '.xhr' if request.xhr?
    super options
  end

This works well in Rails 3, in Rails 2 you can achieve something similar by overriding the default_template_name method like:

private

  def default_template_name
    super + if request.xhr? then '.xhr' else '' end
  end

Upvotes: 2

Related Questions