[Rails] 自訂sanitize
基本使用方式
<%= sanitize @comment.body %>
自定義允許的tags及attributes
<%= sanitize @comment.body, tags: %w(strong em a), attributes: %w(href) %>
全域自定義允許的tags及attributes
# [path] application.rb
config.action_view.sanitized_allowed_tags = %w(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)
config.action_view.sanitized_allowed_attributes = %w(href src style width height alt cite datetime title class name xml:lang abbr)
<%= sanitize @comment.body %>
自定義一個module來使用
class CommentScrubber < Rails::Html::PermitScrubber
def initialize
super
self.tags = %w( form script comment blockquote )
self.attributes = %w( style )
end
def skip_node?(node)
node.text?
end
end
<%= sanitize @comment.body, scrubber: CommentScrubber.new %>
參考
- http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html
- https://ihower.tw/rails/actionview-helpers.html
留言