rails 3 - How to render a PARTIAL as a Json response

前端 未结 3 1666
广开言路
广开言路 2020-12-25 12:04

I want to do something like this:

class AttachmentsController < ApplicationController
  def upload
    render :json => { :attachmentPartial => rende         


        
3条回答
  •  感动是毒
    2020-12-25 12:36

    This should work:

    def upload
        render :json => { :attachmentPartial => render_to_string('messages/_attachment', :layout => false, :locals => { :message => @message }) }
    end
    

    Notice the render_to_string and the underscore _ in before the name of the partial (because render_to_string doesn't expect a partial, hence the :layout => false too).


    UPDATE

    If you want to render html inside a json request for example, I suggest you add something like this in application_helper.rb:

    # 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 you can just do this in your method:

    def upload
      with_format :html do
        @html_content = render_to_string partial: 'messages/_attachment', :locals => { :message => @message }
      end
      render :json => { :attachmentPartial => @html_content }
    end
    

提交回复
热议问题