I am trying to decode some HTML entities, such as '<'
becoming '<'
.
I have an old gem (html_helpers) but it seems to have been abandoned twice.
Any recommendations? I will need to use it in a model.
I am trying to decode some HTML entities, such as '&lt;'
becoming '<'
.
I have an old gem (html_helpers) but it seems to have been abandoned twice.
Any recommendations? I will need to use it in a model.
To encode the characters, you can use CGI.escapeHTML
:
string = CGI.escapeHTML('test "escaping" <characters>')
To decode them, there is CGI.unescapeHTML
:
CGI.unescapeHTML("test "unescaping" <characters>")
Of course, before that you need to include the CGI library:
require 'cgi'
And if you're in Rails, you don't need to use CGI to encode the string. There's the h
method.
<%= h 'escaping <html>' %>
HTMLEntities can do it:
: jmglov@laurana; sudo gem install htmlentities
Successfully installed htmlentities-4.2.4
: jmglov@laurana; irb
irb(main):001:0> require 'htmlentities'
=> []
irb(main):002:0> HTMLEntities.new.decode "¡I'm highly annoyed with character references!"
=> "¡I'm highly annoyed with character references!"
HTMLEntities
gem deals with cases such as å
and —
which CGI.unescapeHTML
does not.
I think Nokogiri gem is also a good choice. It is very stable and has a huge contributing community.
Samples:
a = Nokogiri::HTML.parse "foo bär"
a.text
=> "foo bär"
or
a = Nokogiri::HTML.parse "¡I'm highly annoyed with character references!"
a.text
=> "¡I'm highly annoyed with character references!"
CGI.escapeHTML
maybe unable to solve some cases. In the other hand, if you need a full set of support, I'm sure Nokogiri
is a good choice.
CGI::escapeHTML
doesn't escape German characters like äöüß, and maybe more ... With Nokogiri I didn't checked yet, but this would be a plus point.
To decode characters in Rails use:
<%= raw '<html>' %>
So,
<%= raw '<br>' %>
would output
<br>
#raw
doesn't decode anything. It tells the view not to encode the string. It does this by wrapping the string in a ActiveSupport::SafeBuffer
, which in turn has a flag (html_safe?
), set to true. The view uses this flag to determine that the string can be injected directly into the HTML without being escaped. I like to think of html_safe
as an indication by the programmer that the string in question has already been properly escaped.
Nov 27, 2013 at 0:20
If you don't want to add a new dependency just to do this (like HTMLEntities
) and you're already using Hpricot
, it can both escape and unescape for you. It handles much more than CGI
:
Hpricot.uxs "foo bär"
=> "foo bär"
In Rails we can use:
ERB::Util.html_escape
and ERB::Util.url_encode
.
In views, these are aliased as h
and u
http://ruby-doc.org/stdlib-1.9.3/libdoc/erb/rdoc/ERB/Util.html
<% str="<h1> Test </h1>" %>
result: < h1 > Test < /h1 >
<%= CGI.unescapeHTML(str).html_safe %>