Rails去除Html标签
文章目录
strip_tags(html)
ActionView::Helpers::SanitizeHelper 中的 strip_tags 可以移除 HTML 标签及注释。它使用 html-scanner tokenizer,因此解析能力受 html-scanner 限制。
源码位置:actionpack/lib/action_view/helpers/sanitize_helper.rb。
示例
strip_tags("Strip <i>these</i> tags!")
# => Strip these tags!
strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...")
# => Bold no more! See more here...
strip_tags("<div id='top-bar'>Welcome to my website!</div>")
# => Welcome to my website!
源码
以下为原文记录的第 83 行方法实现:
def strip_tags(html)
self.class.full_sanitizer.sanitize(html).try(:html_safe)
end
在控制器外调用时,可以使用:
ActionController::Base.helpers.strip_tags