1

I'm trying to dynamically add contents of a div using JS. Back end is Ruby on Rails. I am having a problem. Here's what is included in the view file:

var product_sidebar_inner = "<%= CGI.escapeHTML(render(...some partial...)).gsub(/\r/," ").gsub(/\n/," ") %>";

document.getElementById("left_sidebar_wrapper").innerHTML = unescape(product_sidebar_inner);

The above inserts html as text to div#left_sidebar_wrapper. Spent some time on this but still can't make this work. Any idea what am I am doing wrong?

2 Answers 2

1

Based on your comment to macarthy, I think you want CGI.escape (or CGI.unescape), that's what you use for URL encoding. You can also use URI.escape (or URI.unescape) but you'll get tired of having to pass the unsafe regex all the time to get it to do what you want.

Also, on the JavaScript side, you should be using encodeURI or encodeURIComponent as escape is deprecated because it has problems with non-ASCII characters.

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

Comments

0

THink you need to use raw

unescape(raw(product_sidebar_inner));

1 Comment

Well actually problem is on Ruby side. CGI.escapeHTML() escapes a test <h1> tag as '&lt;h1&gt;Test h1 -- escapeHTML&lt;/h1&gt;', while JS escape() produces '%3Ch1%3ETest%20h1%20--%20escapeHTML%3C/h1%3E'. Latter is the right one as it will be unescaped by JS nicely. So I need a function in RoR that produces result equivalent to JS escape()

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.