我将如何使用 sanitize,但告诉它禁止某些默认启用的标签?文档说明我可以把它放在我的application.rb
config.after_initialize do
ActionView::Base.sanitized_allowed_tags.delete 'div'
end
我可以将其作为参数传递给消毒吗?
我将如何使用 sanitize,但告诉它禁止某些默认启用的标签?文档说明我可以把它放在我的application.rb
config.after_initialize do
ActionView::Base.sanitized_allowed_tags.delete 'div'
end
我可以将其作为参数传递给消毒吗?
是的,您可以在每次调用的基础上指定允许哪些标签和属性。来自精美手册:
自定义使用(只允许提到的标签和属性,没有别的)
<%= 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(/</, "<")
end
end
options[:tags]
in的默认值tokenize
和使用的方式options[:tags]
很process_node
有趣,它告诉我们如果options[:tags]
有任何东西,那么它必须包含整个允许的标签集,并且没有任何其他选项可以控制标签集。
此外,如果我们查看sanitize_helper.rb
,我们会发现它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' ] %>
使用标准的默认标签,除了<div>
.
我知道您正在寻找一种传递标签的方法,因此 mu 的答案看起来不错!
我热衷于在全球范围内设置它们,这比我希望的要棘手,因为 ActionView::Base 已覆盖 sanitized_allowed_tags= 以追加而不是替换!
我最终在我的 application.rb 中得到了以下内容:
SANITIZE_ALLOWED_TAGS = %w{a ul ol li b i}
config.after_initialize do
ActionView::Base.sanitized_allowed_tags.clear
ActionView::Base.sanitized_allowed_tags += SANITIZE_ALLOWED_TAGS
end