ruby-on-rails - 如何从 Rails html 中去除标签和样式规则
问题描述
我想使用 sanitize 去除样式标签和嵌入的 css 规则。如下所示:
ActionController::Base.helpers.sanitize("<style> .emphasized { font-weight: bold } </style> hey <div class='emphasized'>watch out</div>", tags: %w(strong b br p ul li em u))
=> " .emphasized { font-weight: bold } hey watch out"
但仍然给我CSS规则。我是否必须使用 Nokogiri 或其他东西,或者可以消毒处理这个?
解决方案
也许您可以尝试定义一个自定义洗涤器。例如
class MyScrubber < Rails::Html::PermitScrubber
def initialize
super
self.tags = %w(strong b br p ul li em u)
end
def scrub(node)
node.name == 'style' ? node.remove : super(node)
end
end
ActionController::Base.helpers.sanitize("<style> .emphasized { font-weight: bold } </style> hey <div class='emphasized'>watch out</div>", scrubber: MyScrubber.new)
推荐阅读
- sql - Oracle 对多个窗口的第一次和最后一次观察
- html - 用户登录后,如何在每个页面上隐藏/禁用注册和登录按钮?
- jquery - 对 Flask 服务的 Ajax GET 请求失败并返回奇怪的空对象,但粘贴到地址栏时相同的 URL 有效
- c++ - IPOPT 不服从约束但在使用 CppAD 时不记录违规
- apache-spark - spark ml 管道 - 标记字段中有 2 个类,但 spark 无法运行二项式回归
- mysql - 错误 #1241 SQL 查询
- pycharm - 为什么 JetBrains YAML 选项卡设置被禁用?
- amazon-web-services - Aws 证书管理器 api 不显示导入的证书
- php - 如何在 Angular4 中使用 php 文件?
- install4j - 使用不同的编译器变量自动构建?