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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4810584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:12:18  来源:igfitidea点击:

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

ruby-on-railsruby-on-rails-3

提问by AnApprentice

I want to do something like this:

我想做这样的事情:

class AttachmentsController < ApplicationController
  def upload
    render :json => { :attachmentPartial => render :partial => 'messages/attachment', :locals => { :message=> @message} }
  end

Is there a way to do this? render a Partial inside a JSON object? thanks

有没有办法做到这一点?在 JSON 对象中呈现 Partial?谢谢

回答by mbillard

This should work:

这应该有效:

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

Notice the render_to_stringand the underscore _in before the name of the partial (because render_to_string doesn't expect a partial, hence the :layout => falsetoo).

注意部分名称之前的render_to_string和下划线_(因为 render_to_string 不期望部分,因此:layout => false也是)。



UPDATE

更新

If you want to render htmlinside a jsonrequest for example, I suggest you add something like this in application_helper.rb:

例如,如果您想htmljson请求中呈现,我建议您在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

回答by jibai31

This question is a bit old, but I thought this might help some folks.

这个问题有点老了,但我认为这可能会帮助一些人。

To render an htmlpartial in a jsonresponse, you don't actually need the with_formathelper as explained in mbillard's answer. You simply need to specify the format in the call to render_to_string, like formats: :html.

要在json响应中呈现html部分,您实际上并不需要帮助程序,如 mbillard 的回答中所述。您只需要在对 的调用中指定格式,例如.with_formatrender_to_stringformats: :html

def upload
  render json: { 
    attachmentPartial: 
      render_to_string(
        partial: 'messages/attachment', 
        formats: :html, 
        layout: false, 
        locals: { message: @message }
      )
  }
end