Ben
Ben

Reputation: 1368

Encode/escape HTML string in Ruby on Rails

I have a string that came from a field in my model.

# <br />
"This is my title with break &lt;br /&gt; in the middle"

I'm rendering it on my view:

<p>
  <%= raw @model.title %>
</p>

Which outputs something like this:

<p>
  This is my title with break <br /> in the middle
</p>

However, the <br /> shows up as string and not as html. Any ideas?

Thanks!

Upvotes: 0

Views: 2792

Answers (1)

Justin Vu
Justin Vu

Reputation: 161

Yes, as Dave Newton said, you should unescape then use html_safe. If your html in your model is not complex, you could use CGI.unescapeHTML to unescape. But if it is, I think you should use gem HTMLEntities at http://htmlentities.rubyforge.org/

<p>
  <%= (CGI.unescapeHTML @model.title).html_safe %>
</p>

Upvotes: 4

Related Questions