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.
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.
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.
Marks a string as trusted safe. It will be inserted into HTML with no additional escaping performed.
I assume by encoding you mean the html-escaping:
To put out raw html in Rails 3 you can use three different approaches.
your can use the raw
helper to output raw html
<% some_string = "<div>Hello World!</div>" %>
<%= some_string %>
<!-- outputs: <div>Hello Worlds!</div> -->
<%=raw some_string %>
<!-- outputs: <div>Hello Worlds!</div> -->
more information: ActionView::Helpers::OutputSafetyHelper#raw
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
You can sanitize your output with sanitize
<%=sanitize "<div>Hello World!</div>", tags: %w( div ) %>
more information: ActionView::Helpers::SanitizeHelper#sanitze
Some more Information:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With