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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/692921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:31:29  来源:igfitidea点击:

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

htmlruby-on-railsrubyescapingencode

提问by kch

I have an untrusted string that I want to show as text in an HTML page. I need to escape the chars '<' and '&' as HTML entities. The less fuss the better.

我有一个不受信任的字符串,我想在 HTML 页面中显示为文本。我需要将字符 ' <' 和 ' &'转义为 HTML 实体。越少闹越好。

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 中是否有内置函数,还是应该自己开发?

采纳答案by Trevor Bramble

The hhelper method:

hhelper方法:

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

回答by Christopher Bradford

Checkout the Ruby CGIclass. There are methods to encode and decode HTML as well as URLs.

查看 Ruby CGI类。有一些方法可以对 HTML 和 URL 进行编码和解码。

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

回答by RSK

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>" %>

回答by Viktor Trón

ERB::Util.html_escapecan be used anywhere. It is available without using requirein Rails.

ERB::Util.html_escape可以在任何地方使用。无需require在 Rails 中使用即可使用。

回答by J-_-L

An addition to Christopher Bradford's answer to use the HTML escaping anywhere, since most people don't use CGInowadays, you can also use Rack:

除了克里斯托弗布拉德福德在任何地方使用 HTML 转义的答案之外,由于大多数人现在不使用CGI,您还可以使用Rack

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

回答by Brian R. Bondy

You can use either h()or html_escape(), but most people use h()by convention. h()is short for html_escape()in rails.

您可以使用h()html_escape(),但大多数人h()按惯例使用。 h()html_escape()in rails 的缩写。

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. I.e. it is encoded as &lt;b&gt;Hello World!&lt;/b&gt;.

如果您查看 HTML 源代码:您将看到输出而不实际加粗数据。即它被编码为&lt;b&gt;Hello World!&lt;/b&gt;.

It will appear an be displayed as <b>Hello World!</b>

它将显示为 <b>Hello World!</b>

回答by Dorian

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

回答by Noddinoff

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. The text could include single quotes. If I didn't escape result[r].thtitlein the confirm method, the Javascript would break:

例如,我有一个使用文本字段生成链接的视图result[r].thtitle。文本可以包含单引号。如果我没有result[r].thtitle在 confirm 方法中转义,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 :htmltitle declaration is magically escaped by Rails.

注意::html标题声明被 Rails 神奇地转义了。