Reputation: 1761
In a view, string is escaped by default.
mystring = "A&B: <b>some string here</b>"
<%=mystring%>
mystring
is rendered as:
A&B: <b>some string here</b>
However, I need to have <b></b>
tag rendered and ampersand escaped.
A&B: <b>some string here</b>
html_safe
unescapes both ampersand and <b>
tag. Is there a way to escape special characters like ampersand but not html tags?
Upvotes: 0
Views: 852
Reputation: 1745
You can unescape specific elements using the Ruby's CGI::unescapeElement method. In your case, you would want to use the following:
mystring = CGI::escape_html("A&B: <b>some string here</b>")
# You can replace ["B"] with an array of tags to be escaped, i.e. ["B", "A", "IMG"]
mystring = CGI::unescapeElement(mystring, ["B"])
<%= mystring.html_safe %>
See http://www.ruby-doc.org/stdlib-1.9.3/libdoc/cgi/rdoc/CGI.html for more escaping methods.
Upvotes: 2