为什么 Rails 2 中的 HTML 编码撇号会产生意外结果?
我正在使用 h
对 Rails 2 中的一些文本进行 HTML 编码,但我遇到了撇号问题。更准确地说,我发现我的撇号最终变成了 '
,这显然不是我想要显示的。
任何人都知道为什么会发生这种情况?我的研究表明 HTML 编码不应该影响撇号。
I'm using h
to HTML encode some text in Rails 2, but I'm having problems with apostrophes. To be more exact, I'm finding that my apostrophes end up as '
which is obviously not want I want to display.
Anyone have any ideas why this is happening? My research has implied HTML encoding shouldn't affect apostrophes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个有趣的问题。我发现
h
AKAhtml_escape
处理撇号 AKA"'"
的方式不一致。根据 ERB::Util 2.6.6 的 RDoc:
在 IRB 中我看到:
编辑:
嘿,这是
h
方法中的一个错误,或者至少是一个不一致。来源如下:注意到传递给
gsub
的字符串不包含"'"
吗?这意味着不会针对单引号/撇号调用 ESCAPE_TABLE 的查找。而且,我们都知道饼干的关键是撇号。 :-)
我希望如果我查看您的 Rails 版本中
h
或html_escape
的定义,我们会发现撇号包含在该字符串中。修复方法是升级您的 ERB/Erubis,或者覆盖
h
/html_escape
定义以使其正确。您可以使用上面的定义作为起点。This is an interesting question. I'm seeing an inconsistency in how
h
AKAhtml_escape
handles apostrophe AKA"'"
.According to the RDoc for ERB::Util 2.6.6:
In IRB I see:
EDIT:
Heh, it's a bug, or at least an inconsistency, in the
h
method. Here's the source:Notice the string being passed to
gsub
doesn't contain"'"
? That means the lookup for ESCAPE_TABLE doesn't get called for single-quote/apostrophe.And, we all know the crux of the biscuit is the apostrophe. :-)
I expect that if I look at the definition for
h
orhtml_escape
in your version of Rails, we'll find the apostrophe is included in that string.The fix is either to upgrade your ERB/Erubis, or override the
h
/html_escape
definition to be correct. You can use the definition above as a starting point.我在 Rails 4 中遇到了类似的问题,其中撇号将显示为
'
问题实际上似乎是我使用
truncate
函数来显示文本。删除后,撇号将按预期显示。在这种情况下,添加
escape:false
作为截断选项可以解决问题。I had similar problem in Rails 4 where apostrophes would display as
'
The problem actually seems to be that I was using the
truncate
function to display the text. Once that was removed, the apostrophes display as expected.In this case adding
escape:false
as option to truncate solves the problem.Ruby on Rails 3 自动执行
h
。这不再需要了。使用而不是
如果您确实想输出任何内容而不转义它,请使用
raw
:Ruby on Rails 3 does
h
automatically. This is not needed anymore. Useinstead of
If you do want to output anything without escaping it, use
raw
:从
actionpack/lib/action_view/erb/util.rb
中查看源代码,撇号没有编码,只有& 。 > < “
字符。我的猜测是您的 Rails 应用程序中的某个库/插件/gem 重新定义了
html_escape
或HTML_ESCAPE
常量。您还应该直接检查数据在数据库中,以确保保存时尚未对其进行编码。From looking the source code in
actionpack/lib/action_view/erb/util.rb
apostrophes aren't encoded, only& > < "
characters.My guess is somewhere in your Rails app a library/plugin/gem has redefined
html_escape
or theHTML_ESCAPE
constant. You should also check your data directly in the database to ensure that it hadn't already been encoded when saved.