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

actionview, format, partial, render, ruby-on-rails

Solution

Building on roninek's response, I've found the best solution to be the following:

in /app/helpers/application.rb:

def with_format(format, &block)
  old_format = @template_format
  @template_format = format
  result = block.call
  @template_format = old_format
  return result
end

In /app/views/foo/bar.json:

<% with_format('html') do %>
  <%= h render(:partial => '/foo/baz') %>
<% end %>

An alternate solution would be to redefine `render` to accept a `:format` parameter.

I couldn't get `render :file` to work with locals and without some path wonkiness.

Problem

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.

Original source

Related problems