Ruby on Rails: render HTML as a single line of a line

Is there a way to render the html.erb part as one line of a line?

I am trying to make the _foo.html.erb part inside javascript so that I can use the whole html document as a string variable.

I tried the following code:

var foo = "<%= render :partial => "foo" %>"; 

And inside _foo.html.erb, let's say I have the following:

 <h1>Hello</h1> <p>World</p> 

This method will give me a syntax error in javascript, because in partial there is CRLF. But if I write code like ...

 <h1>Hello</h1>" + "<p>World</p> 

Now this is not a bug in javascript. I can do the latter way, but it is a disaster if the partial contains many lines of code with a ruby ​​script.

Will there be an alternative way?

Thanks in advance.

+7
javascript ruby-on-rails-3 partial render
source share
2 answers

Use the escape_javascript function:

 var foo = "<%= escape_javascript(render :partial => 'foo') %>"; 
+14
source share

Quick and dirty hack:

 var foo = "<%= render(:partial => "foo").gsub(/[\n\r]/, ' ') %>"; 

It just replaces the newlines with spaces, not-op from the point of view of the HTML parser.

However, this is a rather fragile way to create JavaScript objects. You will need to consider quotation marks in partial, which will make your JavaScript invalid, etc. I would suggest trying to create JavaScript templates for the HTML you want to display and populate them with JSON versions of your models.

+1
source share

All Articles