Casual Coder
Casual Coder

Reputation: 1492

Rendering partial from js.erb template produces content with html tags' remnants

I have a problem with rendering @results from show.js.erb. Output looks like:output from show.js.erb template

show.js.erb

$('#results').empty();
$('#results').html("<ul><%= escape_javascript(render(@results)).html_safe %></ul>");

_result.html.erb

<li>
  <%= link_to(result.title, result.uri) %><br>
  <span class="urls"><%= result.uri %></span>
</li>

Using _result.html.erb in show.html.erb:

<ul>
  <%= render @results %>
</ul>

produces correct output.

The suspected culprit is <%= escape_javascript(render(@results)).html_safe %>. I've tried <%= raw(escape_javascript(render@results)) %> but with no luck. App is created with Rails 3.0.8.

Edit 1:

Longer version of show.js.erb:

$('#results').empty();
$('#results').html("<ul><%= escape_javascript(render(:partial => "results/result",   :collection => @results)).html_safe %></ul>");

output stays the same as on the image with a>, li> and whatnot.

Edit 2:

HTML rendered by show.js.erb: enter image description here

Edit 3:

<a href="http://jasonseifer.com/2010/04/06/rake-tutorial">Rake Tutorial | Jason Seifera&gt;<br>  <span class="urls">http://jasonseifer.com/2010/04/06/rake-tutorialspan&gt;li&gt;</span></a>

Edit 4:

without html_safe:

$('#results').empty();
$('#results').html('<ul><%= escape_javascript render(@results) %></ul>');

Output:

output without html_safe

The </ are already eaten by escape_javascript.

Edit 5: It is working! Finally!

$('#results').html('<%= escape_javascript("<ul>#{render(@results)}</ul>").html_safe %>');

It is Dogbert's answer with .html('') quotes and .html_safe.

Upvotes: 3

Views: 10381

Answers (3)

Jake Jones
Jake Jones

Reputation: 1170

https://github.com/rails/rails/issues/1553 Try this with Rails 3.0.7?

Upvotes: 1

Dogbert
Dogbert

Reputation: 222080

Please try using this for your js.erb

$('#results').html(<%= escape_javascript "<ul>#{render(@results)}</ul>"%>);

Upvotes: 9

natedavisolds
natedavisolds

Reputation: 4295

Two idea here:

  1. Missing a ; after empty()

    $('#results').empty();
    
  2. I've had trouble with using short-hand renders but the long version always works.

    $('#results').html("<ul><%= escape_javascript(render( :partial => "results/result", :collection => @results)).html_safe %></ul>");
    

Next try

Change the double quotes to single quotes on the .html('')

Upvotes: 3

Related Questions