Method: ActionView::Helpers::SanitizeHelper#sanitize
- Defined in:
- actionview/lib/action_view/helpers/sanitize_helper.rb
#sanitize(html, options = {}) ⇒ Object
Sanitizes HTML input, stripping all but known-safe tags and attributes.
It also strips href/src attributes with unsafe protocols like javascript:
, while also protecting against attempts to use Unicode, ASCII, and hex character references to work around these protocol filters. All special characters will be escaped.
The default sanitizer is Rails::Html::SafeListSanitizer. See Rails HTML Sanitizers for more information.
Custom sanitization rules can also be provided.
Please note that sanitizing user-provided text does not guarantee that the resulting markup is valid or even well-formed.
Options
-
:tags
- An array of allowed tags. -
:attributes
- An array of allowed attributes. -
:scrubber
- A Rails::Html scrubber or Loofah::Scrubber object that defines custom sanitization rules. A custom scrubber takes precedence over custom tags and attributes.
Examples
Normal use:
<%= sanitize @comment.body %>
Providing custom lists of permitted tags and attributes:
<%= sanitize @comment.body, tags: %w(strong em a), attributes: %w(href) %>
Providing a custom Rails::Html scrubber:
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 %>
See Rails HTML Sanitizer for documentation about Rails::Html scrubbers.
Providing a custom Loofah::Scrubber:
scrubber = Loofah::Scrubber.new do |node|
node.remove if node.name == 'script'
end
<%= sanitize @comment.body, scrubber: scrubber %>
See Loofah’s documentation for more information about defining custom Loofah::Scrubber objects.
To set the default allowed tags or attributes across your application:
# In config/application.rb
config.action_view. = ['strong', 'em', 'a']
config.action_view.sanitized_allowed_attributes = ['href', 'title']
82 83 84 |
# File 'actionview/lib/action_view/helpers/sanitize_helper.rb', line 82 def sanitize(html, = {}) self.class.safe_list_sanitizer.sanitize(html, )&.html_safe end |