如何呈现字符串的部分? [英] How do I render a partial to a string?
问题描述
如何呈现字符串的部分内容,以便将其作为 JSON 响应的一部分包含在内?我必须将其放入 JSON 响应中,以便为可能的错误消息留出空间.以下代码给出了 500 服务器错误.如果我只使用普通的 render
,那么令人惊讶的是它可以工作.好吧,它只发送回无法解析为 Javascript 的纯 HTML.
代码
respond_to do |format|format.html { redirect_to post_path(post) }格式.js {{错误: "",内容:(render_to_string 部分:'/comments/comment',本地人:{comment:comment},布局:false)}}结尾
错误
<块引用>模板丢失缺少模板注释/创建,应用程序/创建 {:locale=>[:en], :formats=>[:js, :html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder,:haml]}.搜索: * "C:/Users/Chloe/workspace/project/app/views"
有效,但发回纯 HTML
render partial: '/comments/comment', locals: {comment: comment}, layout: false
好的,我明白了.我必须添加 render json:
.我以为我以前试过,它给了我一个双重渲染错误.我想当你 render_to_string
时,有不止一个渲染就可以了.
respond_to do |format|format.html { redirect_to post_path(post) }格式.js {渲染json:{错误:闪光[:错误],内容:(render_to_string 部分:'/comments/comment',本地人:{comment:comment},布局:false)}}结尾
How do I render a partial to a string, so I can include it as part of a JSON response? I have to put it into a JSON response to allow room for a possible error message. The following code gives a 500 server error. If I use just a plain render
, then surprisingly it works. Well, it send back just plain HTML which cannot be parsed as Javascript.
Code
respond_to do |format|
format.html { redirect_to post_path(post) }
format.js {
{
error: "",
content: (render_to_string partial: '/comments/comment', locals: {comment: comment}, layout: false )
}
}
end
Error
Template is missing Missing template comments/create, application/create with {:locale=>[:en], :formats=>[:js, :html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :haml]}. Searched in: * "C:/Users/Chloe/workspace/project/app/views"
Works, but send back plain HTML
render partial: '/comments/comment', locals: {comment: comment}, layout: false
Ok I got it. I had to add render json:
. I thought I had tried that before and it gave me a double render error. I guess when you render_to_string
, then it's ok to have more than one render.
respond_to do |format|
format.html { redirect_to post_path(post) }
format.js {
render json: {
error: flash[:error],
content: (render_to_string partial: '/comments/comment', locals: {comment: comment}, layout: false )
}
}
end
这篇关于如何呈现字符串的部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!