views:

266

answers:

1

Hi guys,

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 cause encoding. Seems that it was changed in Rails 3. How can insert html fragment without encoding in Rails 3?

Regards, Alexey.

+3  A: 

I assume by encoding you mean the html-escaping:

To put out raw html in Rails 3 you can use two 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> -->
    
  2. You can mark the string as html_safe

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

Some more Information:

jigfox
This is correct, but I think it's worth noting that often the more safe way to do it is to use `<%= content_tag :div, "Hello World!" %>` That doesn't involve any marking of potentially dangerous strings as safe.
AlexC
You are right if the text is as simple as in the example, but I believe the Hello World is an example text for something that the OP has stored in the DB so he can't use `content_tag` because it could also be anything but a `<div/>` containing everything, and there could be any number of html tags within this div. if you take the example, the easiest and also fastest way would be to pass on erb completely and just write `<div>Hello World</div>` outside of any erb tag
jigfox