I have an RHTML view in Rails, where the output is coming from my MongoDB collection. The data is outputted correctly using an iteration block, but whenever I try and have HTML tags in my database, they are not rendered in the HTML output, instead they are just displayed.
<%
@posts.find().each do |post|
%>
<h1><%=post["name"]%></h1>
<p><%=post["body"] %></p>
<p><%=post["timestamp"]%></p>
<%
end
%>
But, for instance, if I had
<p>Test</p>
In my database, the tags would be rendered, instead of being printed.
This is a security precaution that is now built into Rails 3. It prevents XSS (cross-site scripting) issues.
If you add raw
you'll get the output you want.
<% @posts.each do |post| %>
<h1><%=raw post["name"]%></h1>
<p><%=raw post["body"] %></p>
<p><%=raw post["timestamp"]%></p>
<% end %>
However, if you are storing user-created arbitrary HTML, I don't recommend you do this unless you are sanitizing the input prior to storing it in the database.
Edit:
Another option: Using the sanitize
helper in place of raw
, e.g. <%=sanitize post["name"], :tags => "p" %>
to allow <p>
tags.