Rails清理删除默认允许的标签

问题描述 投票:2回答:2

我将如何使用清除功能,但告诉它禁止某些默认标记启用? documentation指出我可以将其放入application.rb

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

我可以将其作为参数进行消毒吗?

ruby-on-rails ruby-on-rails-3 sanitize
2个回答
19
投票

是,您可以指定每个呼叫允许哪些标签和属性。从fine manual

自定义使用(仅允许使用提及的标签和属性,而没有其他限制)

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

但是问题是:tags必须包含all您要允许的标签。

sanitize文档说

有关可用选项的完整文档,请参见ActionView :: Base。

但是文档只是一个谎言,ActionView::Base没有对可用选项进行任何说明。

因此,像往常一样,我们必须深入研究源代码,并希望他们不要默默地更改界面。追溯代码yields this

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

options[:tags]tokenize的默认值以及options[:tags]中使用process_node的方式很有趣,告诉我们,如果options[:tags]有任何内容,则它必须包括整个允许的标记集,并且没有其他控制标签集的选项。

[此外,如果我们查看sanitize_helper.rb,我们会看到sanitized_allowed_tags只是白名单消毒剂中sanitized_allowed_tags的包装:

allowed_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' ] %> 除外。


2
投票

我知道您正在寻找一种传递标签的方法,为此,亩的答案看起来不错!

我很想在全球范围内设置它们,这比我希望的要棘手,因为ActionView :: Base已覆盖sanitized_allowed_tags =来添加而不是替换!

我最终在我的application.rb中得到了以下内容:

<div>
© www.soinside.com 2019 - 2024. All rights reserved.