0

I am having problems returning javascript from helper functions. I am unable to get the following test case to work:

function in helpers/application_helper.rb

def show_stuff
    return '$("div#flash").html("<p> stuff </p>");'
end

now I try to call this helper function in general.js.erb

<%= show_stuff %>

Here is the output

$(&quot;div#flash&quot;).html(&quot;&lt;p&gt; stuff &lt;/p&gt;&quot;);

I've also tried show_stuff.html_safe and raw show_stuff and had no luck. I feel the issue is Rails auto-escaping html but have been unable to find a solution.

thekeele
  • 3
  • 1
  • 1
    Try [this article](http://stackoverflow.com/questions/3932267/dont-escape-html-in-ruby-on-rails) and/or [this article](http://stackoverflow.com/questions/5811488/ruby-on-railss-content-for-will-do-an-automatic-html-escape). Also, note that your ruby method doesn't need `return` since it always returns the last line's value anyway. – meetamit Oct 23 '12 at 21:23

1 Answers1

0

ERB is escaping the characters in your outputted Javascript.

To prevent this happening use the raw method in your template.

<%= javascript_tag do %>
    <%= raw(show_stuff) %>
<% end %>

I've added the javascript_tag method around this for context.

Douglas F Shearer
  • 25,952
  • 2
  • 48
  • 48