Last Updated: February 25, 2016
·
10.86K
· mbillard

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

2 Responses
Add your response

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 ·