0

I am trying to do a simple thing where:

_flash.js.erb:

$("#alerts").append("<%=j render :template => "shared/_flash.html.erb" %>");

Note the <%=j... which escapes the javascript.

_flash.html.erb:

<% flash.each do |key, value| %>
  <div class="alert-message top <%= "#{key}" %> fade in" data-alert="alert">
    <a class="close" href="#">x</a>
    <p><%=j value %></p>
  </div>
<% end %>

When _flash.js.erb is called, however, something like the following is appended:

$("#alerts").append("  \u003Cdiv class=alert-message top warning fade in data-alert=alert\u003E
    \u003Ca class=close href=#\u003Ex\u003C/a\u003E
    \u003Cp\u003ELooks like you have already linked with Facebook.\u003C/p\u003E
  \u003C/div\u003E
");

Without the javascript escaping, the response is like this:

$("#alerts").append("  <div class="alert-message top warning fade in" data-alert="alert">
    <a class="close" href="#">x</a>
    <p>Looks like you have already linked with Facebook.</p>
  </div>
");

In the first response, TOO much stuff is escaped. In the second response, nothing is escaped and the double quotes mess things up.

What is the recommended way in rails 3 to achieve the above in a robust fashion?

1
  • So turns out that using escape_javascript(...) instead of <%=j .. %> yields the desired results. Weird - thought they were the same thing. I guess I will have to settle with more verbosity. Any less verbose alternatives or a way to make <%=j ... %> work? Commented Jan 21, 2012 at 23:23

1 Answer 1

3

Use escape_javascript instead; you're JSON-escaping it.

You could alias something the same way j is an alias to json_escape; it's just a helper.

Sign up to request clarification or add additional context in comments.

1 Comment

Someone needs to fix these docs then --api.rubyonrails.org/classes/ActionView/Helpers/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.