【问题标题】:Rails trying to strip html and white list, but sanitize not workingRails 试图剥离 html 和白名单,但清理不工作
【发布时间】:2015-12-12 05:52:36
【问题描述】:
这是我当前的工作代码:
= auto_link(strip_tags(simple_format(truncate(user.notes, :length => 150, :separator => " ", :escape => false))),html: { target: '_blank' })
我正在使用富文本编辑器,我想将 href 或 a 标签列入白名单,但 sanitize 方法对我不起作用,只有 strip_tags 删除了我想要的 HTML 标签。
如何使用strip_tags 加入白名单?
【问题讨论】:
标签:
html
ruby-on-rails
ruby-on-rails-4
sanitize
strip-tags
【解决方案1】:
也许你应该试试sanitizeGEM。
对于富编辑器,我建议在将内容保存到数据库时进行清理,而不是在要显示内容时进行清理。它更安全。
这就是我在我的项目中使用的before_save,清理价值。
safe_value = Sanitize.fragment(value,
:elements => %w{a b br em i li ol p strong u ul},
:attributes => {'a' => ['href'], 'p' => ['style'], 'ol' => ['style'], 'ul' => ['style'], 'li' => ['style']},
:add_attributes => {'a' => {'rel' => 'nofollow'}}, # nofollow for SEO
:protocols => {'a' => {'href' => ['http', 'https']}},
:css => {:properties => ['text-align', 'margin-left']})
只需根据需要调整选项即可。