gpt4 book ai didi

ruby-on-rails - rails 3 - 如何将 PARTIAL 渲染为 Json 响应

转载 作者:行者123 更新时间:2023-12-04 05:31:54 25 4
gpt4 key购买 nike

我想做这样的事情:

class AttachmentsController < ApplicationController
def upload
render :json => { :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 和下划线 _在局部名称之前(因为 render_to_string 不期望局部,因此 :layout => false 也是)。

更新

如果要渲染 html里面 json例如请求,我建议您在 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

关于ruby-on-rails - rails 3 - 如何将 PARTIAL 渲染为 Json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4810584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com