Grnbeagle
Grnbeagle

Reputation: 1761

Rails 3: Escape string in the view but not all

In a view, string is escaped by default.

mystring = "A&B: <b>some string here</b>" 
<%=mystring%>

mystring is rendered as:

A&amp;B: &lt;b&gt;some string here&lt;/b&gt;

However, I need to have <b></b> tag rendered and ampersand escaped.

A&amp;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

Answers (2)

Dan
Dan

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

mikdiet
mikdiet

Reputation: 10018

You can split string on parts, then unescape some you want

Upvotes: 0

Related Questions