Ruby-on-rails 在 js.erb 文件中渲染部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11127934/
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
Rendering partial in js.erb file
提问by mbajur
I'm trying to create an ajax-based comment form which will update my comments list when submitted. Pretty basic stuff.
我正在尝试创建一个基于 ajax 的评论表单,它将在提交时更新我的评论列表。很基本的东西。
I have a partial comments/_single.html.hamlwhich has a single <li>tag with basic comment info and here is my comments/create.js.erbfile (actually these are three different test files merged into one to show you what my problem is):
我有一个部分comments/_single.html.haml,它有一个<li>带有基本评论信息的标签,这是我的comments/create.js.erb文件(实际上,这些是三个不同的测试文件合并为一个以向您展示我的问题所在):
$('#comments ul.comments').append("<%= render :partial => 'comments/single', :locals => { :c => @comment } %>");
$('#comments ul.comments').append("<%= render :partial => 'comments/foobar' %>");
$('#comments ul.comments').append("foobar");
alert('foobar');
The content for comments/_foobar.html.hamlis just foobar, no html inside.
My problem is that first two lines doesn't work. There are no errors in my dev server console, object inspector says that comment code was returned correctly but they are not added to my comments list. The third line works fine and so the fourth one. It looks like there are some problems with using render.
内容comments/_foobar.html.haml只是foobar,里面没有 html。我的问题是前两行不起作用。我的开发服务器控制台中没有错误,对象检查器说正确返回了评论代码,但它们没有添加到我的评论列表中。第三行工作正常,所以第四行。使用render.
回答by SuperMaximo93
When rendering partials inside Javascript code, you should use the escape_javascript method, like so
在 Javascript 代码中渲染部分时,您应该使用 escape_javascript 方法,就像这样
$('#comments ul.comments').append("<%= escape_javascript render(:partial => 'comments/single', :locals => { :c => @comment }) %>");
This method is aliased as j, so you can also do this
这个方法别名为j,所以你也可以这样做
$('#comments ul.comments').append("<%= j render(:partial => 'comments/foobar') %>");
The method Escapes carriage returns and single and double quotes for JavaScript segments ActionView::Helpers::JavaScriptHelper Rails docs
方法为 JavaScript 段转义回车和单引号和双引号 ActionView::Helpers::JavaScriptHelper Rails docs

