rails 3 - 如何将 PARTIAL 渲染为 Json 响应 [英] rails 3 - How to render a PARTIAL as a Json response
本文介绍了rails 3 - 如何将 PARTIAL 渲染为 Json 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做这样的事情:
class AttachmentsController < ApplicationController
def upload
render :json => { :attachmentPartial => render :partial => 'messages/attachment', :locals => { :message=> @message} }
end
有没有办法做到这一点?在 JSON 对象中呈现 Partial?谢谢
Is there a way to do this? render a Partial inside a JSON object? thanks
推荐答案
这应该有效:
def upload
render :json => { :attachmentPartial => render_to_string('messages/_attachment', :layout => false, :locals => { :message => @message }) }
end
注意部分名称之前的 render_to_string 和下划线 _
(因为 render_to_string 不需要部分,因此 :layout =>也是错误的).
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).
更新
例如,如果您想在 json
请求中呈现 html
,我建议您在 application_helper.rb
中添加如下内容:
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
这篇关于rails 3 - 如何将 PARTIAL 渲染为 Json 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文