开发者

RHTML displaying HTML tags on output

开发者 https://www.devze.com 2023-01-30 12:16 出处:网络
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, th

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开发者_JS百科 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.


Apart from raw and .html_safe, which give 100% trust to the user's input, you could also use sanitize to restrict only a number of tags that allowed.

<%= sanitize post["name"] $>

For the details, see: http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

0

精彩评论

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

关注公众号