Render an HTML partial inside a JSON request
Note that this also works for rendering any view (partials or not) of any format within a request of any format.
First, add the following method into a helper (application_helper.rb
for example):
# execute a block with a different format (ex: an html partial while in an ajax request)
def with_format(format, &block)
old_formats = formats
self.formats = [format]
block.call
self.formats = old_formats
nil
end
Then whenever you have a JSON request, do this in the method:
def controller_action
with_format :html do
@html_content = render_to_string :partial => 'path/to/view', :locals => { /* any locals needed in the view */ }
end
render :json => { :html_content => @html_content }
end
Written by Michel Billard
Related protips
2 Responses
why not just
render partial: 'json_partial', formats: [:json], locals: { foo: @bar }
?
over 1 year ago
·
@rwz this will render only the partial (instead of your normal action). You can not include other arguments and I think there are other issues with that method, although I do not remember them (because that was what I first tried).
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#