我需要允许"style=position: absolute;"
的内联sanitize(post.content)
输出。我发现documentation for Rails 4说
config.action_view.sanitized_allowed_css_properties = ['position']
在application.rb中会添加属性到白名单,但我找不到文档是否仍然是Rails 5的情况,并且它在多次重启服务器后似乎没有工作。有没有办法轻松添加白名单css属性?这个answer for Rails 4建议一个猴子补丁,但我不知道在哪里或如何这样做。
更新:安装gem rails-deprecated_sanitized允许上面的配置行工作,所以看起来不推荐使用sanitized_allowed_css_properties。当然有一种方法可以在Rails 5中做到这一点?我不能退回到4,我需要将内联样式位置列入白名单,以便让第三方插件工作(CKEditor + Iframely)
您可以在Loofah for Rails 5清洁剂中将多个CSS属性添加到白名单。
Loofah::HTML5::WhiteList::ALLOWED_CSS_PROPERTIES.merge %w(position background-image left list-style min-width top z-index)
在application.rb
上添加以上行(再次不确定这是多么安全)
使用this answer和默认允许的属性here列表,我最终添加了
default_tags = Loofah::HTML5::WhiteList::ALLOWED_CSS_PROPERTIES.add('position')
到application.rb,它允许位置默认通过清理。不确定这是多么安全。
我完全不知道@Jim Hogan试图用他的答案做什么。我尝试过它并没有用。所以我花了一点时间来分析一切,我找到了自己的答案:
我们从sanitize_css
得到了一个名叫ActionController::Base.helpers
的帮手。
那么为什么不通过提取原始样式来使用它呢? Nokogiri包含在Rails> 4中。
def patched_sanitize(html_tag_string)
sanitize html_tag_string, tags: %w(a b strong), attributes: manual_attributes
end
def manual_attributes
attributes = %w(href target align)
attributes << 'style' unless style_unsafe?
attributes
end
def style_unsafe?
ActionController::Base.helpers.sanitize_css(style_attributes_of(string)).empty?
end
def style_attributes_of(string)
Nokogiri::HTML(self.body).xpath('//body').children.map{|e| e.attr('style')}.join(' ')
end
编辑:好的我想我终于明白了OP想说的话。并且出于某种原因,只有当我做了我在这个答案中所做的事情时才会工作。所以我的答案是补充我猜:)