1

I have some simple erb code in one of my views in a rails project.

<%= comment.body %>

I'd like the html tags in the comment.body to be preserved as they have formatting information. I've verified that the text is saved in the database properly like

<b>hello</b>

However it turns out on the page to be <b>hello</b> not hello as I expect.

How could this be? I'm not using <%= h to escape the html code.

How do I make it not escaping? I'm using rails 3. Does this matter?

timeon
  • 2,194
  • 4
  • 18
  • 19
  • possible duplicate of [Disable HTML escaping in erb templates](http://stackoverflow.com/questions/4699497/disable-html-escaping-in-erb-templates) – coreyward Jun 16 '11 at 04:39
  • Quick answer: Rails 3 calls `h` by default. This is a duplicate question though. – coreyward Jun 16 '11 at 04:40

2 Answers2

5

You can also use sanitize.

<%= sanitize(comment.body) %>

sanitize will leave html code but escape javascript.

Msencenb
  • 5,675
  • 11
  • 52
  • 84
2

Rails 3 now automatically escapes your output.

To unescape the text and use the actual tags, use raw(...):

<%= raw(comment.body) %>

However, be careful with this, as it will allow any tags, including scripts (potentially malicious). A safer option might be to have users use markdown-formatted text or something similar, rather than allowing raw HTML tags.

Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • Thanks for a clear answer and the extra useful information. I tried tinymce hammer plugin, and it is filtering out tags such as – timeon Jun 16 '11 at 05:54