Rails 4.2.10中sanitize不支持RGB颜色的问题求助
解决Rails 4.2.10中Sanitize过滤RGB格式颜色的问题
这个问题是因为Rails默认的WhiteListSanitizer在处理CSS style属性时,默认不允许rgb()格式的颜色值——它只认可命名颜色(比如red)或者十六进制颜色(比如#e25041)。要让RGB颜色生效,我们需要调整sanitizer的CSS规则配置。
方案一:全局配置(推荐,一次修改全项目生效)
在你的Rails项目中新建一个初始化文件,比如config/initializers/sanitizer.rb,添加以下代码:
# 允许sanitizer接受RGB格式的颜色值 Rails::Html::WhiteListSanitizer.allowed_css_function_values.add('rgb') # 如果还需要支持RGBA,可以一起加上 # Rails::Html::WhiteListSanitizer.allowed_css_function_values.add('rgba')
修改完成后重启Rails服务器,之后你原来的sanitize调用就能正常保留RGB格式的color样式了:
<%= sanitize @record.notes, tags: %w(strong em u div span br h1 h2 h3 h4 ul ol li table thead tbody th tr td img hr a), attributes: %w(style colspan rowspan text-align class href target src) %>
方案二:自定义Helper方法(适合局部需求)
如果不想全局修改,也可以在app/helpers/application_helper.rb中定义一个自定义的sanitize方法:
def custom_sanitize(content) sanitizer = Rails::Html::WhiteListSanitizer.new # 设置允许的标签和属性,和你原来的参数一致 sanitizer.allowed_tags = %w(strong em u div span br h1 h2 h3 h4 ul ol li table thead tbody th tr td img hr a) sanitizer.allowed_attributes = %w(style colspan rowspan text-align class href target src) # 允许color这个CSS属性 sanitizer.allowed_css_properties = ['color'] # 添加rgb函数到允许的CSS函数列表 sanitizer.allowed_css_function_values = ['rgb'] # 如果你需要保留命名颜色,可以加上这些关键字值 # sanitizer.allowed_css_keyword_values = ['red', 'blue', 'green', ...] sanitizer.sanitize(content) end
然后在视图中替换原来的sanitize调用:
<%= custom_sanitize @record.notes %>
原理说明
Rails的sanitize方法依赖Loofah库处理HTML清理,其中针对CSS样式的过滤由WhiteListSanitizer的规则控制。默认情况下,allowed_css_function_values集合里没有包含rgb,所以当检测到style="color: rgb(226, 80, 65);"时,会认为这个样式值不合法,进而清空整个style属性。添加rgb到允许列表后,sanitizer就会保留这种格式的颜色值了。
内容的提问来源于stack exchange,提问作者tquill
相关产品推荐
相关产品推荐

