Reputation: 4474
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
.
Upvotes: 49
Views: 65022
Reputation: 2056
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
Upvotes: 121