Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 789
mbajur Avatar asked Jun 20 '12 20:06

mbajur


People also ask

What is Escape_javascript?

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").

What are partials in rails?

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.


1 Answers

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

like image 166
SuperMaximo93 Avatar answered Sep 22 '22 00:09

SuperMaximo93