开发者

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

My question relate开发者_JAVA百科s 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?


Short answer:

<%= html_to_show.html_safe %>

Long answer:

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


<%= raw html_to_show %>

That should do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜