<%= raw @event.description %>
<%= @event.description.html_safe %>
使用raw和html_safe可以使输入的html代码完整输出,但也会使输入的js代码完整输出,会造成XSS 跨站脚本攻击,除非知道输入的人是自己人,不会黑自己的网站,否则用sanitize替代
<%= sanitize @event.description %>
sanitize默认的白名单是
- 允许的 HTML 标籤 strong em b i p code pre tt samp kbd var sub sup dfn cite big small
address hr br div span h1 h2 h3 h4 h5 h6 ul ol li dl dt dd abbr acronym a img
blockquote del ins
- 允许的 HTML 属性 href src width height alt cite datetime title class name xml:lang abbr
如果要将 table 跟 style 加入白名单,我们需要自己加。请修改 config/application.rb
config.action_view.sanitized_allowed_tags = Rails::Html::WhiteListSanitizer.allowed_tags + %w(table tr td)
config.action_view.sanitized_allowed_attributes = Rails::Html::WhiteListSanitizer.allowed_attributes + %w(style border)
# or
config.action_view.sanitized_allowed_attributes = Rails::Html::SafeListSanitizer.allowed_attributes.merge(['style', 'color'])
config.action_view.sanitized_allowed_tags = Rails::Html::SafeListSanitizer.allowed_tags.merge(['table', 'thead', 'tbody', 'tr', 'td', 'font'])