futureshocked
futureshocked

Reputation: 2105

Rails 3: how to reverse ERB "<%=" default behaviour so I can inject HTML?

My question relates to this one, but I am trying to reverse the default Rails 3 behavior of "<%=" so that I can inject HTML.

In my scenario, I have an old Rails 2 plug that generates HTML. My view will then need to inject this HTML in the page.

When this plugin creates HTML like this stored in a variable html_to_show:

<p class="notice"><span></span>Sorry about this, but we have a problem...</p><p class="error"><span></span>Cannot go to next step</p>

and in the view I try to show the contents of html_to_show like this:

<%= html_to_show %>

... what I get in my browser is this:

&lt;p class="notice"&gt;&lt;span&gt;&lt;/span&gt;Sorry about this, but we have a problem...&lt;/p&gt;&lt;p class="error"&gt;&lt;span&gt;&lt;/span&gt;Cannot go to next step&lt;/p&gt;

How can I get Rails 3 to inject the contents of html_to_show exactly as it is, without any sanitization?

Upvotes: 0

Views: 1633

Answers (2)

vonconrad
vonconrad

Reputation: 25377

Short answer:

<%= html_to_show.html_safe %>

Long answer:

Rails escapes all html to protect from XSS attacks. Adding .html_safe prevents the escaping.

Upvotes: 7

DigitalRoss
DigitalRoss

Reputation: 146053

<%= raw html_to_show %>

That should do it.

Upvotes: 3

Related Questions