简体   繁体   English

如何HTML编码/转义字符串?有内置的吗?

[英]How to HTML encode/escape a string? Is there a built-in?

I have an untrusted string that I want to show as text in an HTML page. 我有一个不受信任的字符串,我想在HTML页面中显示为文本。 I need to escape the chars ' < ' and ' & ' as HTML entities. 我需要将字符' < '和' & '作为HTML实体转义。 The less fuss the better. 越少越好。

I'm using UTF8 and don't need other entities for accented letters. 我正在使用UTF8,并且不需要其他实体用于重音字母。

Is there a built-in function in Ruby or Rails, or should I roll my own? Ruby或Rails中是否有内置函数,或者我应该自己编写?

Checkout the Ruby CGI class. 签出Ruby CGI类。 There are methods to encode and decode HTML as well as URLs. 有一些方法可以编码和解码HTML以及URL。

CGI::escapeHTML('Usage: foo "bar" <baz>')
# => "Usage: foo &quot;bar&quot; &lt;baz&gt;"

h辅助方法:

<%=h "<p> will be preserved" %>

In Ruby on Rails 3 HTML will be escaped by default. 在Ruby on Rails 3中,HTML默认会被转义。

For non-escaped strings use: 对于非转义字符串,请使用:

<%= raw "<p>hello world!</p>" %>

ERB::Util.html_escape can be used anywhere. ERB :: Util.html_escape可以在任何地方使用。 It is available without using require in Rails. 它在Rails中不使用require即可使用。

An addition to Christopher Bradford's answer to use the HTML escaping anywhere, since most people don't use CGI nowadays, you can also use Rack : 除了克里斯托弗·布拉德福德在任何地方使用HTML转义的答案,因为现在大多数人都不使用CGI ,你也可以使用Rack

require 'rack/utils'
Rack::Utils.escape_html('Usage: foo "bar" <baz>')

You can use either h() or html_escape() , but most people use h() by convention. 您可以使用h()html_escape() ,但大多数人按惯例使用h() h() is short for html_escape() in rails. h()是rails中html_escape()

In your controller: 在你的控制器中:

@stuff = "<b>Hello World!</b>"

In your view: 在你看来:

<%=h @stuff %>

If you view the HTML source: you will see the output without actually bolding the data. 如果您查看HTML源:您将看到输出而不实际加粗数据。 Ie it is encoded as &lt;b&gt;Hello World!&lt;/b&gt; 即它被编码为&lt;b&gt;Hello World!&lt;/b&gt; .

It will appear an be displayed as <b>Hello World!</b> 它将显示为<b>Hello World!</b>

Comparaison of the different methods: 比较不同的方法:

> CGI::escapeHTML("quote ' double quotes \"")
=> "quote &#39; double quotes &quot;"

> Rack::Utils.escape_html("quote ' double quotes \"")
=> "quote &#x27; double quotes &quot;"

> ERB::Util.html_escape("quote ' double quotes \"")
=> "quote &#39; double quotes &quot;"

I wrote my own to be compatible with Rails ActiveMailer escaping: 我自己编写了与Rails ActiveMailer转义兼容:

def escape_html(str)
  CGI.escapeHTML(str).gsub("&#39;", "'")
end

h() is also useful for escaping quotes. h()对于转义引号也很有用。

For example, I have a view that generates a link using a text field result[r].thtitle . 例如,我有一个视图,使用文本字段result[r].thtitle生成链接。 The text could include single quotes. 该文本可能包括单引号。 If I didn't escape result[r].thtitle in the confirm method, the Javascript would break: 如果我没有在confirm方法中转义result[r].thtitle ,则Javascript会中断:

&lt;%= 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 %>

&lt;a href="#" onclick="if (confirm('docs: add column &amp;apos;dummy&amp;apos; will be removed')) { new Ajax.Request('/resource/delete_resourced/837?owner=386&amp;th=511', {asynchronous:true, evalScripts:true, method:'delete', parameters:'authenticity_token=' + encodeURIComponent('ou812')}); }; return false;" title="&lt;= Remove">docs: add column 'dummy'</a>

Note: the :html title declaration is magically escaped by Rails. 注意:: :html标题声明被Rails神奇地转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM