如何剥离& 从一个字符串?

Vic*_*tor 6 ruby-on-rails

使用RoR 2.3.8

name 有价值 Tiffany & Co.

此代码在视图中:

@header_title = 'Related shops with ' + strip_tags(@shop.name)
Run Code Online (Sandbox Code Playgroud)

结果结果A:

#note that the & has NOT been stripped
Related shops with Tiffany & Co.
Run Code Online (Sandbox Code Playgroud)

此代码在视图中:

@header_title = strip_tags(@shop.name) + 'Related shops with '
Run Code Online (Sandbox Code Playgroud)

得到结果B:

#note that the & HAS been stripped
Tiffany & Co. Related shops with
Run Code Online (Sandbox Code Playgroud)

我其实想要Related shops with Tiffany & Co.(即转换&&)

我该怎么做呢?

为什么在第二次通话中,&被剥离,但在第一次通话中却不是这样?

Hei*_*kki 6

一个猜测:

@header_title = ('Related shops with ' + strip_tags(@shop.name)).html_safe
Run Code Online (Sandbox Code Playgroud)

在您的示例中,&在任何一种情况下都不会被剥离.如果字符串未标记为html safe,则在添加到视图时默认情况下会将其转义,因此如果您检查页面源,则会&变为&.

替代什么时候@header_title不是html安全,你将它添加到erb视图:

<%= raw @header_title %>
Run Code Online (Sandbox Code Playgroud)

这个'html安全'与Rails XSS保护有关:

请注意,您应该使用html_saferaw只有当你信任字符串的内容.

- 编辑

在Rails 3控制台中测试后编辑了答案.仍然不知道为什么订单在那里很重要.

ruby-1.8.7-p330 :020 > ('Related shops with ' + helper.strip_tags("Tiffany &amp; Co.")).html_safe?
 => false 
ruby-1.8.7-p330 :021 > (helper.strip_tags("Tiffany &amp; Co.") + 'Related shops with ').html_safe?
 => true 
ruby-1.8.7-p330 :022 > ('Related shops with ' + helper.strip_tags("Tiffany &amp; Co.")).html_safe.html_safe?
 => true
Run Code Online (Sandbox Code Playgroud)

--edit2

进一步测试..在连接安全和不安全的字符串时看起来顺序很重要.

ruby-1.8.7-p330 :037 > safe = "This is html safe string".html_safe
 => "This is html safe string" 
ruby-1.8.7-p330 :038 > not_safe = "This is not html safe string"
 => "This is not html safe string" 
ruby-1.8.7-p330 :039 > (safe + not_safe).html_safe?
 => true 
ruby-1.8.7-p330 :040 > (not_safe + safe).html_safe?
 => false
Run Code Online (Sandbox Code Playgroud)