Alexey Zakharov
Alexey Zakharov

Reputation: 25102

Html escaping in a Rails 3 view

I'm using Rails 3. I want to display generated html fragment inside erb template

<%= "<div>Foo Bar</div>" %>

Rails encodes div tags.

If I'm correct in Rails 2 <%=h causes html escaping. Seems that it was changed in Rails 3. How can insert html fragment without encoding in Rails 3?

Regards, Alexey.

Upvotes: 11

Views: 5729

Answers (1)

jigfox
jigfox

Reputation: 18185

I assume by encoding you mean the html-escaping:

To put out raw html in Rails 3 you can use three different approaches.

  1. your can use the raw helper to output raw html

    <% some_string = "<div>Hello World!</div>" %>
    <%= some_string %>
    <!-- outputs: &lt;div&gt;Hello Worlds!&lt;/div&gt; -->
    <%=raw some_string %>
    <!-- outputs: <div>Hello Worlds!</div> -->
    

    more information: ActionView::Helpers::OutputSafetyHelper#raw

  2. You can mark the string as html_safe

    <% some_string = "<div>Hello World!</div>".html_safe %>
    <%= some_string %>
    <!-- outputs: <div>Hello World!</div> -->
    

    more information: String#html_safe and ActiveSupport::SafeBuffer#new

  3. You can sanitize your output with sanitize

    <%=sanitize "<div>Hello World!</div>", tags: %w( div ) %>
    

    more information: ActionView::Helpers::SanitizeHelper#sanitze

Some more Information:

Upvotes: 19

Related Questions