Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 438
Alexey Zakharov Avatar asked Aug 26 '10 09:08

Alexey Zakharov


People also ask

Why is HTML escaping?

Escapes are very useful for representing characters that are not apparent or are ambiguous. Numeric or named character references, as well as CSS escapes, can be used to represent characters in HTML style attribute. The style element HTML can not contain numeric or named character references.

How do you escape in Ruby?

When using strings in Ruby, we sometimes need to put the quote we used to define the string inside the string itself. When we do, we can escape the quote character with a backslash \ symbol.

What is Html_safe?

Marks a string as trusted safe. It will be inserted into HTML with no additional escaping performed.


1 Answers

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:

  • SafeBuffers and Rails 3.0
  • Railscast #204: XSS Protection in Rails 3
like image 171
jigfox Avatar answered Oct 02 '22 04:10

jigfox