ruby-on-rails-3erbhtml-escape

How to make html code in erb tag not escaped


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?


Solution

  • 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.