开发者

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

开发者 https://www.devze.com 2023-03-31 15:50 出处:网络
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.

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 =开发者_如何学C>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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号