如何HTML编码/转义string? 有没有内置的?
我有一个不受信任的string,我想在HTML页面中显示为文本。 我需要将字符“ & ”和“ & ”转义为HTML实体。 越less越好。 
我正在使用UTF8,不需要其他实体的重音字母。
在Ruby或Rails中是否有一个内置的函数,还是应该滚动我自己的?
  h帮手法: 
 <%=h "<p> will be preserved" %> 
检出Ruby CGI类。 有方法来编码和解码的HTML以及URL。
 CGI::escapeHTML('Usage: foo "bar" <baz>') # => "Usage: foo "bar" <baz>" 
在Ruby on Rails 3中,HTML将被默认转义。
对于非转义的string使用:
 <%= raw "<p>hello world!</p>" %> 
  ERB :: Util.html_escape可以在任何地方使用。 它可以在Rails中不使用require 。 
 您可以使用h()或html_escape() ,但大多数人使用h()按照惯例。  h()是rails中的html_escape() 。 
在你的控制器中:
 @stuff = "<b>Hello World!</b>" 
在你看来:
 <%=h @stuff %> 
 如果您查看HTML源代码:您将看到输出而不实际加粗数据。 即它被编码为<b>Hello World!</b>  。 
 它会显示为<b>Hello World!</b> 
 除了Christopher Bradford的答案,在任何地方都可以使用HTML转义,因为现在大多数人不使用CGI ,你也可以使用Rack : 
 require 'rack/utils' Rack::Utils.escape_html('Usage: foo "bar" <baz>') 
比较不同的方法:
 > CGI::escapeHTML("quote ' double quotes \"") => "quote ' double quotes "" > Rack::Utils.escape_html("quote ' double quotes \"") => "quote ' double quotes "" > ERB::Util.html_escape("quote ' double quotes \"") => "quote ' double quotes "" 
我写我自己与Rails的ActiveMailer转义兼容:
 def escape_html(str) CGI.escapeHTML(str).gsub("'", "'") end 
  h()对于转义引号也很有用。 
 例如,我有一个使用文本字段result[r].thtitle生成链接的视图。 文本可以包括单引号。 如果我没有在确认方法中转义result[r].thtitle ,那么Javascript将会中断: 
 <%= link_to_remote "#{result[r].thtitle}", :url=>{ :controller=>:resource, :action =>:delete_resourced, :id => result[r].id, :th => thread, :html =>{:title=> "<= Remove"}, :confirm => h("#{result[r].thtitle} will be removed"), :method => :delete %> <a href="#" onclick="if (confirm('docs: add column &apos;dummy&apos; will be removed')) { new Ajax.Request('/resource/delete_resourced/837?owner=386&th=511', {asynchronous:true, evalScripts:true, method:'delete', parameters:'authenticity_token=' + encodeURIComponent('ou812')}); }; return false;" title="<= Remove">docs: add column 'dummy'</a> 
 注意: :html标题声明被Rails神奇地转义了。