Rails3 和安全的 nl2br ! [英] Rails3 and safe nl2br !
问题描述
我有一个用户可以发表评论的系统.
I have a system for the users to be able to post comments.
评论被抓取到一个文本区域.
The comments are grasped into a textarea.
我的问题是用 br 标签格式化注释以替换 \n
My problem is to format the comments with br tag to replace \n
事实上,我可以这样做
s.gsub(/\n/, '
')
但是包含在 rails 中的 xss 保护会转义 br 标签.
But the xss protection including in rails escapes br tags.
所以我可以这样做
s.gsub(/\n/, '
').html_safe
但是,所有的标签都被接受了,即使是脚本......造成了很大的安全问题
But then, all the tags are accepted even script.... causing a big security problem
所以我的问题是:如何安全地使用 br 格式化文本?
So my question is : how to format text with br safely ?
谢谢
现在,我已经添加了这个
For now, i have add this
def sanitaze
self.gsub(/(<.*?>)/, '')
end
def nl2br
self.sanitaze.gsub(/\n/, '<br />').html_safe
end
推荐答案
正如 Ryan Bigg 所建议的那样,simple_format
是完成这项工作的最佳工具:它安全"且比其他解决方案更简洁.
As Ryan Bigg suggested simple_format
is the best tool for the job: it's 'l safe' and much neater than other solutions.
对于@var:
<%= simple_format(@var) %>
如果您需要清理文本以去除 HTML 标签,您应该在将其传递给 simple_format
If you need to sanitize the text to get rid of HTML tags, you should do this before passing it to simple_format
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
这篇关于Rails3 和安全的 nl2br !的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!