views:

892

answers:

3

I'm using jQuery with rails and have the following piece of code

$('#related').html("<%= render :partial => "related_items" %>");

I'm having a problem in the browser where the content of the #related element is only being replaced when there are no line breaks in the partial.

This isn't too much of a big deal, I can place everything on one one line but it makes the code very difficult to read.

Is there a way around having to omit line breaks in the jQuery html() attribute?

A: 

...Wait, isn't that code supposed to be processed before javascript is even ran? Or are you trying to print code in plain-text for educational reasons?

Jonathan Sampson
Sorry, I should have explained. This is a js.erb file so the ruby side is executed before it's sent to the browser.
KJF
+2  A: 

Whats happening here is the code between the <% and %> is being interpreted by Rails first, and the output of that interpretation is being sent to the browser. So what's being sent to the browser is:

$('#related').html("Some text with a
line break in it");

This is not valid javascript because javascript doesn't allow multi-line double-quoted strings. You need to escape the line breaks in the string so that when they are printed to the browser the result is a valid javascript statement.

Matt Bridges
Didn't realise this was not valid javascript. That makes sense. I'll escape it on the ruby side.
KJF
+1  A: 

And just for completeness, this is what I have done to get things working.

$('#related').html("<%= escape_javascript(render :partial => "related_items") %>");
KJF