Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render HTML from a Rails instance variable?

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!

like image 904
Stirman Avatar asked Jun 24 '10 23:06

Stirman


2 Answers

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 %>
like image 118
iblue Avatar answered Sep 19 '22 11:09

iblue


<%= @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.

like image 43
Nicolas Viennot Avatar answered Sep 21 '22 11:09

Nicolas Viennot