2

サニタイズを使用するにはどうすればよいですか?ただし、デフォルトで有効になっているタグの一部を許可しないように指示しますか? ドキュメントには、これを私の中に入れることができると記載されていますapplication.rb

config.after_initialize do
  ActionView::Base.sanitized_allowed_tags.delete 'div'
end

代わりに、これをサニタイズの引数として渡すことはできますか?

4

2 に答える 2

20

はい、呼び出しごとに許可するタグと属性を指定できます。細かいマニュアルから:

カスタム使用(上記のタグと属性のみが許可され、それ以外は許可されません)

<%= sanitize @article.body, :tags => %w(table tr td), :attributes => %w(id class style) %>

しかし、それに関する問題は、許可したいすべて:tagsのタグを含める必要があるということです。

sanitizeドキュメントには次のように書かれています

使用可能なオプションの完全なドキュメントについては、ActionView::Baseを参照してください。

しかし、ドキュメントは嘘でありActionView::Base、利用可能なオプションについては何も述べていません。

したがって、いつものように、ソースを掘り下げて、インターフェイスが黙って変更されないことを期待する必要があります。コードを少しトレースすると、のようになります。

def tokenize(text, options)
  options[:parent] = []
  options[:attributes] ||= allowed_attributes
  options[:tags]       ||= allowed_tags
  super
end

def process_node(node, result, options)
  result << case node
    when HTML::Tag
      if node.closing == :close
        options[:parent].shift
      else
        options[:parent].unshift node.name
      end

      process_attributes_for node, options

      options[:tags].include?(node.name) ? node : nil
    else
      bad_tags.include?(options[:parent].first) ? nil : node.to_s.gsub(/</, "&lt;")
  end
end

inのデフォルト値とoptions[:tags]inで使用されるtokenize方法は興味深いものであり、何かがある場合は、許可されたタグのセット全体を含める必要があり、タグセットを制御するための他のオプションはないことを示しています。options[:tags]process_nodeoptions[:tags]

また、を見ると、これはホワイトリストサニタイザーのラッパーにすぎないsanitize_helper.rbことがわかります。sanitized_allowed_tagsallowed_tags

def sanitized_allowed_tags
  white_list_sanitizer.allowed_tags
end

このようなことを行う独自のヘルパーを追加できるはずです(テストされていない頭のてっぺんのコード):

def sensible_sanitize(html, options)
  if options.include? :not_tags
    options[:tags] = ActionView::Base.sanitized_allowed_tags - options[:not_tags]
  end
  sanitize html, options
end

そして、あなたは

<%= sensible_sanitize @stuff, :not_tags => [ 'div' ] %>

を除く標準のデフォルトタグを使用します<div>

于 2011-09-24T23:13:44.770 に答える