Rails 3 - 如何将局部视图渲染为Json响应

27

我想要做类似这样的事情:

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

有没有办法在JSON对象中呈现Partial(部分视图)? 谢谢


是的,您应该能够完成这个任务。不过我认为您的语法有误。请查看以下链接获取一个可用的版本:https://dev59.com/RXI95IYBdhLWcg3w7SpZ - raidfive
1
问题不同 :),部分使用 JSON,而不是在部分中使用 JSON。 - Rishav Rastogi
不错的发现 :) 我猜我从来没有尝试过这种方式 - raidfive
我在这里回答了一个类似的问题,链接为http://stackoverflow.com/a/15574453/667598。 - hisa_py
3个回答

45

这应该可以运行:

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

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


更新

如果您想在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

4
只是想提一下,mbillard的解决方案在我添加了.html后缀到部分路径之后才为我找到了部分内容,我认为这可能是因为默认情况下它使用了json格式。 - Noz
@CyleHunter,这实际上是一个非常常见的用例,我编辑了我的答案来涵盖这种行为。 - mbillard
1
Rails 3.2:您还可以在render_to_string中设置处理程序(haml、erb等),例如,render_to_string(partial:'messages/attachment',handlers:[:haml]) - Luke W

12

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

要在 json 响应中呈现一个 html 部分,您实际上不需要像 mbillard 的答案中解释的那样使用 with_format 辅助函数。您只需在调用 render_to_string 时指定格式,如 formats::html

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

这个解决了我的问题!但愿这个额外选项被记录下来了 :( - Andrés Mejía

1
在Rails 6中,我认为这与被接受的答案有些不同。我认为您不需要在局部名称中设置下划线。这对我有效:
format.json {
  html_content = render_to_string(partial: 'admin/pages/content', locals: { page: @page }, layout: false, formats: [:html])
  render json: { attachmentPartial: html_content }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接