强制在Rails中的HTML转义3 [英] Forcing HTML Escaping in Rails 3

查看:129
本文介绍了强制在Rails中的HTML转义3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,rails自动转义。它目前认为一个字符串是html_safe(它是),但是为了显示,我需要它仍然逃避html。这是字符串正在执行的步骤。

I'm running into an issue with the rails auto-escaping. It currently thinks a string is html_safe (which it is), but for display purposes I need it to still escape the html. Here's the steps the string is taking.

my_string = render(:partial => "set_string", :locals => {:item => @item})
<%= my_string %>

,部分基本上是

<h2>Page Header</h2>
<strong><%= item.name %></strong>
<%= item.body %>
etc

我的理解是,因为我直接在视图中显示文本h2等),它假定它是安全的,它也正确地转义了项目输出,这使得整个my_string安全。所以,当我尝试用

My understanding is that because I'm displaying text in a view directly (the h2, etc) it assumes it is safe, and it also properly escapes the item outputs, which makes the whole my_string safe. So, when I try to display it with the

<%= my_string %>

它不会转义剩余的html。我尝试添加h强制逃脱,但是没有工作。

It doesn't escape the remaining html. I tried adding h to force the escaping but that didn't work.

所以我的问题是,有没有办法强制html转义一个安全的字符串,而不是调用字符串上的东西,这将使它不安全?

So my question is, is there anyway to force html escaping of a safe string other than calling something on the string that will make it unsafe?

非常感谢您的帮助。

推荐答案

感谢Sebastien的建议,我想在这里得到真正的答案,而不是埋在评论中:

Thanks to Sebastien for the suggestion, I wanted to get the real answer here and not buried in the comments:

我看起来像这样:

<%= raw CGI::escapeHTML(my_string) %>

您需要原始调用,否则escapeHTML使字符串不安全,除了转义它自动逃脱双重转义。

You need the "raw" call otherwise the escapeHTML makes the string unsafe in addition to escaping it so the auto escape double escapes it.

这篇关于强制在Rails中的HTML转义3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆