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
.
a> This what escape_javascript does. It makes sure that the string returned will not "break" javascript. If you use it, you will get the desired output: $("#reviews").
A partial allows you to separate layout code out into a file which will be reused throughout the layout and/or multiple other layouts. For example, you might have a login form that you want to display on 10 different pages on your site.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With