I\'m trying to generate a JSON response that includes some HTML. Thus, I have /app/views/foo/bar.json.erb
:
{
someKey: \'some value\',
someH
For Rails 3, the with_format block works, but it's a little different:
def with_format(format, &block)
old_formats = formats
self.formats = [format]
block.call
self.formats = old_formats
nil
end
I had a file named 'api/item.rabl' and I wanted to render it from an HTML view so I had to use:
render file: 'api/item', formats: [:json]
(file
because the file have no underscore in the name, formats
and not format
(and passes and array))
Just elaborating on what zgchurch wrote:
Thought it might be useful.
def with_format(format, &block)
old_formats = formats
begin
self.formats = [format]
return block.call
ensure
self.formats = old_formats
end
end
What's wrong with
render :partial => '/foo/baz.html.erb'
? I just tried this to render an HTML ERB partial from inside an Atom builder template and it worked fine. No messing around with global variables required (yeah, I know they have "@" in front of them, but that's what they are).
Your with_format &block approach is cool though, and has the advantage that you only specify the format, whereas the simple approach specifies the template engine (ERB/builder/etc) as well.
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.
Beginning with Rails 3.2.3, when calling render :partial (only works outside of the respond_to
block).
render formats: [ :html ]
instead of
render format: 'html'