41

In a Rails 3 application I have a domain class where one attribute stores pure HTML content (it's a blog app, the domain class is Post).

In the ERB templates, I need to display the content of the attribute as it was formmated, with the HTML tags in place. But, Rails is escaping all HTML tags! How can I disable this behaviour for this class attribute?

Example:

somePost = Post.new
somePost.content = "<strong> Hi, i'm here! </strong>"

In the erb template:

<%= somePost.content %>

The HTML generated is escaped:

&lt;strong&gt; Hi, i'm here! &lt;/strong&gt;
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Lucas
  • 3,059
  • 5
  • 33
  • 48

3 Answers3

62

Try using raw(somePost.content). Alternatively, somePost.content.html_safe.

sevenseacat
  • 24,699
  • 6
  • 63
  • 88
  • 6
    IMHO raw is a little safer than .html_safe because raw(nil) writes "", where nil.html_safe results in an exception. – Fiid Dec 12 '12 at 23:57
  • 2
    .html_safe is an implementation detail of Rails and was never meant for Public-facing API. The `raw(string)` method should be used instead. https://groups.google.com/forum/#!topic/rubyonrails-core/T9N5wexIg80 – aaron-coding Apr 07 '15 at 00:12
  • raw is wrapped in html_safe. They do the same thing except raw also calls .to_s. – Peter Black Jun 23 '17 at 20:28
61

Use raw(string), as described in the release notes.

7.4.3 Other Changes

You no longer need to call h(string) to escape HTML output, it is on by default in all view templates. If you want the unescaped string, call raw(string).

Basically, where you did

<%=h @model.attr %>

before you can now use

<%= @model.attr %>

and where you did that before you can now use

<%=raw @model.attr %>
Community
  • 1
  • 1
Skilldrick
  • 69,215
  • 34
  • 177
  • 229
37

Using a double equals means the result is not escaped...

<%== somePost.content %>

See this SO question about it - What does <%== %> do in rails erb?

Community
  • 1
  • 1
Chris Kimpton
  • 5,546
  • 6
  • 45
  • 72
  • This is the answer I was looking for, not the accepted one :) This is basically equivalent to [using `!=`](http://haml.info/docs/yardoc/file.REFERENCE.html#unescaping_html) (instead of just `=`) in HAML templates. – Tom Lord Dec 14 '16 at 15:25