How to render HTML from a Rails instance variable?
-
29-09-2019 - |
Question
I have an intstance variable I am passing to a view, @body
.
@body
is a string with html in it.
<%= @body %>
renders the string, not the html. How do I render the html in the string?
Possible?
Thanks in advance!
Solution
<%= @body %>
would output some html if you had some html in @body
.
It's a little weird to have html in that variable since the controller is not supposed to pass any HTML (The controller has to be view agnostic).
This is why we have some helper methods. Make a helper method that generates some html, and use it in your view.
OTHER TIPS
The answer is not true anymore. Rails 3 automatically escapes html for you, so when you have in a controller:
@error = "<h1>OMG u broke teh intertubez!!111</h1>"
This will output the HTML without escaping:
<%= raw @error %>
And both of this will escape the HTML:
<%= h @error %>
<%= @error %>