raw vs. html_safe vs. h to unescape html

前端 未结 6 1540

Suppose I have the following string

@x = \"Turn me into a link\"

In my view, I want a link to be displayed.

6条回答
  •  半阙折子戏
    2020-11-22 06:03

    Considering Rails 3:

    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 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.

    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" is a nice explanation on how the SafeBuffers (the class that does the html_safe magic) work.

提交回复
热议问题