Reputation: 9358
Using the raw and html_safe methods with Rails 3.0.10 and I am still unable to unescape the html and get it to display as Content instead of <strong>Content</strong>
.
@object.property.html_safe
gives me <strong>Some content</strong>
<%= raw(@object.property) %>
also gives me <strong>Some content</strong>
I have seen these posts and tried to implement their fixes:
I have also watched the Ryan Bates Railscasts episode about xss protection: http://railscasts.com/episodes/204-xss-protection-in-rails-3?view=comments
I created a helper method based on his example called safe where I made sure the string content had the html_safe method applied:
def safe(content)
"#{content}".html_safe
end
Then I called it on my model: safe(@object.property)
Still the content is not displaying as expected.
I have also tried using the sanitize method, but to no avail.
What could be causing this?
Upvotes: 3
Views: 4892
Reputation: 4524
Here is another option, and perhaps the better one. Use the following snippet.
plain_text = strip_tags(html_input)
Here is the links to docs.enter link description here
Upvotes: 0
Reputation: 9358
Ok, looks like I've got it working now.
Looked in the Ruby docs and found the CGI class and the unescapeHTML method.
I was using a rich text editor in a form to save text to the database. Apparently since the html was sent to the database as escaped, I needed to undo the escaping and then call html_safe on it.
This is how it appears in the database: <strong>howdy</strong>
I applied that to my helper method, and now the html displays as html instead of tags.
def safe(content)
"#{ CGI::unescapeHTML(content) }".html_safe
end
This works, but if there is a better way to handle this scenario I'm open to suggestions.
Update
I was experimenting with Rails helper methods to try and prevent the text from being saved to the database as escaped (which would solve my problem since then I wouldn't have to un-escape it).
As it turns out, the rich text editor that I am using is encoding the html - you have to pass it a property of encoded: false
within the javascripts object literal notation.
So, if you are like me and pulling your hair out trying to find out why Rails is saving text to the database as encoded - you may actually need to tweak configuration on the rich text editor itself.
Now I can remove the CGI class and just use this as a helper:
def safe(content)
"#{ content }".html_safe
end
Hopefully someone else will find this helpful too.
Upvotes: 8