AnA*_*ice 25 ruby-on-rails ruby-on-rails-3
我想做这样的事情:
class AttachmentsController < ApplicationController
def upload
render :json => { :attachmentPartial => render :partial => 'messages/attachment', :locals => { :message=> @message} }
end
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?在JSON对象中渲染部分?谢谢
mbi*_*ard 43
这应该工作:
def upload
render :json => { :attachmentPartial => render_to_string('messages/_attachment', :layout => false, :locals => { :message => @message }) }
end
Run Code Online (Sandbox Code Playgroud)
请注意部分名称之前的render_to_string和下划线_(因为render_to_string不期望部分,因此:layout => false).
UPDATE
例如,如果你想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
Run Code Online (Sandbox Code Playgroud)
然后你可以在你的方法中执行此操作:
def upload
with_format :html do
@html_content = render_to_string partial: 'messages/_attachment', :locals => { :message => @message }
end
render :json => { :attachmentPartial => @html_content }
end
Run Code Online (Sandbox Code Playgroud)
这个问题有点老了,但我认为这可能对某些人有所帮助。
要在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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19472 次 |
| 最近记录: |