How to render HTML from a Rails instance variable?

I have an intstance variable that I pass to the view, @body .

@body is a line with html in it.

<%= @body %> displays a string, not html. How to render html in a string?

Possible?

Thanks in advance!

+6
ruby-on-rails actionview
source share
2 answers

<%= @body %> outputs some html if you have html in @body . It is a little strange to have html in this variable, since the controller should not skip any HTML (the controller should be viewed by an agnostic).

That is why we have helper methods. Create a helper method that generates some html and use it in your view.

+2
source share

The answer is no longer correct. Rails 3 automatically starts html for you, so when you have a controller:

 @error = "<h1>OMG u broke teh intertubez!!111</h1>" 

This will output the HTML without escaping:

 <%= raw @error %> 

And both of these will result in HTML:

 <%= h @error %> <%= @error %> 
+9
source share

All Articles