使用Rails sanitize方法清理HTML时class属性未被移除如何解决?
解决sanitize方法保留p标签class属性的问题
Rails的sanitize方法默认内置了属性白名单,仅通过tags参数指定允许的标签列表,不会对默认允许的属性(包括class、id等)做过滤,因此才会出现class属性被保留的情况。
解决方法
1. 单次调用时指定属性白名单
调用时新增attributes参数,传入你需要保留的属性列表,如果不需要任何属性直接传空数组即可:
ActionController::Base.helpers.sanitize( "hello <p class='MsoNormal'>here</p> i am", tags: %w(strong b br p ul li em u), attributes: [] ) # 输出结果:"hello <p>here</p> i am"
2. 全局配置默认属性白名单
如果需要全项目统一sanitize的属性过滤规则,可以在config/initializers目录下新增初始化文件sanitize_config.rb,修改全局默认配置:
# 全局禁止所有属性,如有需要保留的属性可在数组中添加,例如 %w(href title) Rails.application.config.action_view.sanitized_allowed_attributes = []
3. 自定义过滤规则(仅移除p标签的class属性)
如果只需要过滤p标签的class属性,其他标签的属性保留,可以借助底层依赖的Loofah库自定义scrubber实现:
# 自定义 scrubber,仅移除p标签的class属性 remove_p_class_scrubber = Loofah::Scrubber.new do |node| node.remove_attribute('class') if node.name == 'p' && node.has_attribute?('class') end # 调用sanitize后追加自定义scrubber result = ActionController::Base.helpers.sanitize( "hello <p class='MsoNormal'>here</p> <span class='test'>text</span> i am", tags: %w(strong b br p ul li em u span), attributes: %w(class) ).scrub!(remove_p_class_scrubber) # 输出结果:"hello <p>here</p> <span class='test'>text</span> i am"
内容的提问来源于stack exchange,提问作者ibpix
相关产品推荐
相关产品推荐

