Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

ruby on rails - Rendering partial in js.erb file

I'm trying to create an ajax-based comment form which will update my comments list when submitted. Pretty basic stuff.

I have a partial comments/_single.html.haml which has a single <li> tag with basic comment info and here is my comments/create.js.erb file (actually these are three different test files merged into one to show you what my problem is):

$('#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.haml is 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When rendering partials inside Javascript code, you should use the escape_javascript method, like so

$('#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

$('#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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...