Miguel Ping
Miguel Ping

Reputation: 18337

Rails 3.1: respond_to json request with HTML

Is it possible to respond a json request with html instead of json?

I would like to do this:

respond_to do |format|
  format.html { render 'page' }
  format.json { render 'page' } #render an html page instead of a JSON response
end

but Rails will search for a 'page.json' and will throw an error.

Upvotes: 1

Views: 1987

Answers (2)

Victor Deryagin
Victor Deryagin

Reputation: 12215

You need to explicitly set format, content-type (default is application/json) and layout (default is none):

respond_to do |format|
  format.html { render 'page' }
  format.json do              # render an html page instead of a JSON response
    render 'page.html', {
      :content_type => 'text/html',
      :layout       => 'application'
    }
  end
end

Upvotes: 4

Ben Lee
Ben Lee

Reputation: 53309

Just use the full filename. render 'page.html' (or whatever the file is called).

Note that while this should work, if you're doing this, you're probably doing something wrong. Think about how you can restructure your code so you don't have to bend the rules.

Upvotes: 0

Related Questions