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

时间:2011-04-08 17:08:17

标签: ruby-on-rails

使用RoR 2.3.8

name的值为Tiffany & Co.

此视图中的代码:

@header_title = 'Related shops with ' + strip_tags(@shop.name)

产生结果A:

#note that the & has NOT been stripped
Related shops with Tiffany & Co.

此视图中的代码:

@header_title = strip_tags(@shop.name) + 'Related shops with '

得出结果B:

#note that the & HAS been stripped
Tiffany & Co. Related shops with

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

我该怎么做?

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

1 个答案:

答案 0 :(得分:6)

猜测:

@header_title = ('Related shops with ' + strip_tags(@shop.name)).html_safe

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

@header_title不是html安全且您将其添加到erb视图时替代:

<%= raw @header_title %>

这个'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

- 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