Partial rendering inside js.erb. Is it possible to get a raw string so that I can remove spaces?

I want to do a partial in my js.erb file so that I can use the generated HTML in my Javascript. Here is a sample code.

create.js.erb

$(function(){ var html = "<%= render(:partial => `pretty_box`) %>"; $("#container").prepend(html); }); 

_pretty_box.html.haml

 .pretty_box_container .title Something Pretty 

When render.js.erb is displayed, I get the following:

 $(function(){ var html = "<div class="pretty_box_container> <div class="title"> Something Pretty </div> </div>"; $("#container").prepend(html); }); 

As expected, this breaks my javascript. I need to remove a space from a partial result. The problem is that the return value of render is an ActiveSupport::SafeBuffer object that cancels all the "unsafe" methods (see UNSAFE_STRING_METHODS ), including strip . Therefore, calling render(:partial => pretty_box ).strip HTML encodes the entire string.

I tried all kinds of combinations using the html_safe or to_s . They do not work because they return self , and using raw does not work either because it calls to_s.html.safe .

I know that I can add the characters > and < to my HAML, but I do not want to do this for every line of every partial.

+6
source share
1 answer

The problem is not spaces, but quotation marks.

 $(function(){ var html = "<div class="pretty_box_container> ^ This is where you go wrong 

Try the following:

 $(function(){ var html = "<%= escape_javascript(render(:partial => 'pretty_box')) %>"; $("#container").prepend(html); }); 

Check out this answer on StackOverflow for an explanation of escape_javascript .

+8
source

Source: https://habr.com/ru/post/896103/


All Articles