rails 3 – 如何将PARTIAL呈现为Json响应
我想做这样的事情:
class AttachmentsController { :attachmentPartial => render :partial => 'messages/attachment', :locals => { :message=> @message} } end
有没有办法做到这一点? 在JSON对象中渲染Partial? 谢谢
这应该工作:
def upload render :json => { :attachmentPartial => render_to_string('messages/_attachment', :layout => false, :locals => { :message => @message }) } end
注意部分名称之前的render_to_string和下划线_in(因为render_to_string不期望部分,因此:layout => false )。
UPDATE
例如,如果你想在json
请求中呈现html
,我建议你在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
然后你可以在你的方法中执行此操作:
def upload with_format :html do @html_content = render_to_string partial: 'messages/_attachment', :locals => { :message => @message } end render :json => { :attachmentPartial => @html_content } end
这个问题有点陈旧,但我认为这可能对一些人有所帮助。
要在json响应中呈现html部分,实际上并不需要使用with_format
帮助器,如mbillard的答案中所述。 您只需在render_to_string
调用中render_to_string
formats: :html
,如formats: :html
。
def upload render json: { attachmentPartial: render_to_string( partial: 'messages/attachment', formats: :html, layout: false, locals: { message: @message } ) } end