Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering partial inside js.erb. Is it possible to get raw string so I can strip whitespace?

I want to render a partial in my js.erb file so I can use the generated HTML in my Javascript. Here's some code to serve as an example.

create.js.erb

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

_pretty_box.html.haml

.pretty_box_container
  .title
    Something Pretty

When create.js.erb is rendered, I get the following:

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

As you would expect, this breaks my javascript. I need to strip the whitespace from the result of rendering the partial. The problem is the return value of render is an ActiveSupport::SafeBuffer object, which overrides all "unsafe" methods (see UNSAFE_STRING_METHODS), including strip. So calling render(:partial =>pretty_box).strip HTML-encodes the entire string.

I've tried all sorts of combinations using the methods html_safe or to_s. They don't work because they return self, and using raw doesn't work either because it calls to_s.html.safe.

I know I can append > and < characters to my HAML, but I don't want to do that for every line of every partial.

like image 362
John Avatar asked Aug 29 '11 06:08

John


1 Answers

The problem is not whitespaces, but quotes.

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

Try this:

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

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

like image 95
Mischa Avatar answered Sep 19 '22 04:09

Mischa