替换<code> tags</code>内的所有“&gt;”(&gt;)

时间:2010-06-06 11:04:38

标签: ruby-on-rails ruby

如何将所有&gt;替换为>,将&lt;替换为< <code>代码中的<code>&lt;script&gt;`alert('I steal cookies');`&lt;/script&gt;</code>

例如:

<code><script>alert('I steal cookies);<script><code>

使用:

h()

原因是因为< and >方法会转义所有{{1}}。

1 个答案:

答案 0 :(得分:2)

  

原因是因为h()方法会转义所有<>

该方法正常运行,标签应进行转义。你为什么想要忘掉他们?

如果您不想转义输出(因为您实际上想要输出标签),只需不要调用h()

如果您无法控制h()的调用,那么您可以通过调用字符串上的相应方法将字符串标记为“HTML安全”,然后再将其传递给h()。但是很难说这是否适合你:

s = "<strong>example</strong>".html_safe
h(s) # = "<strong>example</strong>"

或者:

s = "<strong>example</strong>"
s.html_safe!
h(s) # = "<strong>example</strong>"