原始vs. html_safe vs. h来转义html [英] raw vs. html_safe vs. h to unescape html

查看:92
本文介绍了原始vs. html_safe vs. h来转义html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下字符串

@x = "<a href='#'>Turn me into a link</a>"

在我看来,我希望显示一个链接。也就是说,我不希望将@x中的所有内容都转义并显示为字符串。使用

In my view, I want a link to be displayed. That is, I don't want everything in @x to be unescaped and displayed as a string. What's the difference between using

<%= raw @x %>
<%= h @x %>
<%= @x.html_safe %>

推荐答案

考虑Rails 3:

html_safe 实际上将字符串设置为HTML安全(这是一个比这稍微复杂一点,但基本上是这样)。这样,您可以从助手或模型中随意返回HTML安全字符串。

html_safe actually "sets the string" as HTML Safe (it's a little more complicated than that, but it's basically it). This way, you can return HTML Safe strings from helpers or models at will.

h 仅可用于在控制器或视图中,因为它来自助手。它将迫使输出转义。它并不是真的不推荐使用,但是您很可能不再使用它:唯一的用法是还原 html_safe 声明,这很不寻常。

h can only be used from within a controller or view, since it's from a helper. It will force the output to be escaped. It's not really deprecated, but you most likely won't use it anymore: the only usage is to "revert" an html_safe declaration, pretty unusual.

在表达式中加上 raw 实际上等于调用 to_s 链接了 html_safe ,但是在帮助程序上声明,就像 h 一样,因此只能在控制器和视图上使用。

Prepending your expression with raw is actually equivalent to calling to_s chained with html_safe on it, but is declared on a helper, just like h, so it can only be used on controllers and views.

SafeBuffers and Rails 3.0 是有关 SafeBuffer s(执行 html_safe 魔术)工作。

"SafeBuffers and Rails 3.0" is a nice explanation on how the SafeBuffers (the class that does the html_safe magic) work.

这篇关于原始vs. html_safe vs. h来转义html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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