I have the inherited the following string (I can do nothing about the format):
<iframe \n class=\"some_class\"\n type=\"text/html\" \n src=\"/embed/iframe_content.html?id=tsqA5D7_z10\" \n width=\"960\" \n height=\"593\" \n marginwidth=\"0\" \n marginheight=\"0\" \n frameborder=\"0\">\n</iframe>
I am rendering it in an erb template like this:
<%= the_string %>
At the moment it renders as text like this:
<iframe class="some_class" type="text/html" src="/embed/iframe_content.html?id=tsqA5D7_z10" width="960" height="593" marginwidth="0" marginheight="0" frameborder="0"></iframe>
I need to render it as HTML.
I have tried the following:
<%= the_string.html_safe %>
# Renders the string unchanged<%= CGI.unescapeHTML(the_string) %>
# Errors with a Type Error 'can't dup NilClass'<%= CGI.unescapeHTML(the_string).html_safe %>
# Errors with a Type Error 'can't dup NilClass'<%= raw the_string %>
# Renders the string unchangedHow can I render this string as HTML?
One way to unescape HTML entities is to put our escaped text in a text area. This will unescape the text, so we can return the unescaped text afterward by getting the text from the text area. We have an htmlDecode function that takes an input string as a parameter.
The escape() and unescape() functions is to Encode and decode a string in JavaScript. The escape() function in JavaScript to make a string portable to transmit it over a network and we can use unscape() function to get back the original string.
The unescape() function computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The escape sequences might be introduced by a function like escape . Usually, decodeURI or decodeURIComponent are preferred over unescape .
As you seem to have noticed, there are two things you need to take care of:
For number 2 <%= raw ... %>
should work fine.
For number 1 CGI.unescapeHTML
was the right idea, but I don't think it recognizes all HTML entities so I would recommend taking a look at the HTML Entites gem
You can also try and use the simple_format helper method, but I think you are going to have to pass it some options for it to allow the <iframe>
tag
also I would strongly suggest moving your unescaping
logic into a helper method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With