从 rails 中的属性中删除所有 html 标签 [英] Remove all html tags from attributes in rails

查看:78
本文介绍了从 rails 中的属性中删除所有 html 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目模型,它有一些文本属性,一个是摘要.我有一些项目在摘要中包含 html 标签,我想将其转换为纯文本.我有这个方法,它有一个正则表达式,可以删除所有的 html 标签.

I have a Project model and it has some text attributes, one is summary. I have some projects that have html tags in the summary and I want to convert that to plain text. I have this method that has a regex that will remove all html tags.

def strip_html_comments_on_data
  self.attributes.each{|key,value| value.to_s.gsub!(/(<[^>]+>|&nbsp;|\r|\n)/,"")}
end

我也有一个 before_save 过滤器

I also have a before_save filter

before_save :strip_html_comments_on_data

问题是保存项目后html标签还在.我错过了什么?

The problem is that the html tags are still there after saving the project. What am I missing?

而且,是否有一种非常简单的方法可以在所有模型中调用该方法?

And, is there a really easy way to have that method called in all the models?

谢谢,

尼古拉斯·霍克·伊萨

推荐答案

未测试

include ActionView::Helpers::SanitizeHelper

def foo
  sanitized_output = sanitize(html_input)
end

其中 html_input 是包含 HTML 标签的字符串.

where html_input is a string containing HTML tags.

编辑

您可以通过传递 :tags=>[] 作为选项来去除所有标签:

You can strip all tags by passing :tags=>[] as an option:

plain_text = sanitize(html_input, :tags=>[])

虽然阅读了 docs 我发现有一个更好的方法:

Although reading the docs I see there is a better method:

plain_text = strip_tags(html_input)

然后根据 smotchkiss 将其设置为前置过滤器,您就可以开始了.

Then make it into a before filter per smotchkiss and you're good to go.

这篇关于从 rails 中的属性中删除所有 html 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆