Alex Rivera | Logout

How do I render a partial of a different format in Rails?

Asked 2008-12-03T23:26:30.853
130

I'm trying to generate a JSON response that includes some HTML. Thus, I have /app/views/foo/bar.json.erb:

{
  someKey: 'some value',
  someHTML: "<%= h render(:partial => '/foo/baz') -%>"
}

I want it to render /app/views/foo/_baz.html.erb, but it will only render /app/views/foo/_baz.json.erb. Passing :format => 'html' doesn't help.

Edit
Report

2 Answers

25

In Rails 3, the View has a formats array, which means you can set it to look for [:mobile, :html]. Setting that will default to looking for :mobile templates, but fall back to :html templates. The effects of setting this will cascade down into inner partials.

The best, but still flawed way, that I could find to set this was to put this line at the top of each full mobile template (but not partials).

<% self.formats = [:mobile, :html] %>

The flaw is that you have to add that line to multiple templates. If anyone knows a way to set this once, from application_controller.rb, I'd love to know it. Unfortunately, it doesn't work to add that line to your mobile layout, because the templates are rendered before the layout.

answered 2011-05-30T23:17:55.417
17

Just elaborating on what zgchurch wrote:

  • taking exceptions into account
  • returning the result of the called block

Thought it might be useful.

def with_format(format)
  old_formats = formats
  self.formats = [format]
  yield
ensure
  self.formats = old_formats
end
answered 2011-02-22T04:49:00.847

Your Answer