从rails中的属性中删除所有html标记
我有一个Project模型,它有一些文本属性,一个是摘要。 我有一些项目在摘要中有html标签,我想将其转换为纯文本。 我有这个方法有一个正则表达式,将删除所有的HTML标签。
def strip_html_comments_on_data self.attributes.each{|key,value| value.to_s.gsub!(/(]+>| |\r|\n)/,"")} end
我也有一个before_savefilter
before_save :strip_html_comments_on_data
问题是保存项目后html标签仍然存在。 我错过了什么?
并且,是否有一种非常简单的方法可以在所有模型中调用该方法?
谢谢,
NicolásHockIsaza
未经测试
include ActionView::Helpers::SanitizeHelper def foo sanitized_output = sanitize(html_input) end
其中html_input是包含HTML标记的字符串。
编辑
您可以通过传递:tags=>[]
作为选项来剥离所有标记:
plain_text = sanitize(html_input, :tags=>[])
虽然阅读文档我看到有一个更好的方法:
plain_text = strip_tags(html_input)
然后按照每个smotchkiss进入一个前filter,你很高兴去。
最好不要在模型中包含视图助手。 只需使用:
HTML::FullSanitizer.new.sanitize(text)
只需使用zetetic提到的strip_tags()文本助手
首先,这里的问题是Array#each
返回输入数组而不管块内容如何。 在我问的一个问题中,有几个人刚刚和我一起讨论过Array#each
: “在Ruby中返回带有修改值的哈希值” 。
第二,除了Array#each
没有真正做到你想要的东西,我认为你不应该这样做。 为什么需要在所有模型的属性上运行此方法?
最后,为什么不保留用户的HTML输入,只是在输出时使用标准的h()
助手?
# this will output as plain text <%=h string_with_html %>
这很有用,因为您可以查看数据库并查看与用户输入的完全相同的未修改数据(如果需要)。 如果您在保存值之前必须转换为纯文本,@ zetetic的解决方案可以帮助您入门。
include ActionView::Helpers::SanitizeHelper class Comment < ActiveRecord::Base before_save :sanitize_html protected def sanitize_html self.text = sanitize(text) end end
直接参考Rails的清洁剂而不使用包含。
def text ActionView::Base.full_sanitizer.sanitize(html).html_safe end
注意:我附加了.html_safe来制作HTML实体,例如
正确渲染。 如果可能存在恶意JavaScript注入,请不要使用此function。
如果你想删除
除了html标签,还可以使用nokogiri
include ActionView::Helpers::SanitizeHelper def foo sanitized_output = strip_tags(html_input) Nokogiri::HTML.fragment(sanitized_output) end