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

查看:13
本文介绍了raw 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:

Considering Rails 3:

html_safe 实际上将字符串设置"为 HTML Safe(它比这更复杂,但基本上就是这样).这样,您可以随意从帮助程序或模型返回 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 和 Rails 3.0" 是关于 SafeBuffers(执行 html_safe 魔法的类)如何工作的一个很好的解释.

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

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

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