如何在 ruby​​ on Rails 中清理用户生成的 html 代码

发布于 09-25 20:16 字数 115 浏览 9 评论 0原文

我将用户生成的 html 代码存储在数据库中,但某些代码已损坏(没有结束标记),因此当此代码会弄乱页面的整个渲染时。

我如何使用 ruby​​ on Rails 来防止这种行为。

谢谢

I am storing user generated html code in the database, but some of the codes are broken (without end tags), so when this code will mess up the whole render of the page.

How could I prevent this sort of behaviour with ruby on rails.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

和我恋爱吧2024-10-02 20:16:07

使用适当的 HTML 解析器(例如 Nokogiri )来执行此操作并不难,它可以作为处理方法的一部分执行清理操作:

bad_html = '<div><p><strong>bad</p>'

puts Nokogiri.fragment(bad_html).to_s
# <div><p><strong>bad</strong></p></div>

一旦正确解析,您应该拥有完全平衡的标签。

It's not too hard to do this with a proper HTML parser like Nokogiri which can perform clean-up as part of the processing method:

bad_html = '<div><p><strong>bad</p>'

puts Nokogiri.fragment(bad_html).to_s
# <div><p><strong>bad</strong></p></div>

Once parsed properly, you should have fully balanced tags.

荭秂2024-10-02 20:16:07

我的 google-fu 显示点击量出人意料地少,但这里是最热门的:)

有效的格式正确的 HTML

My google-fu reveals surprisingly few hits, but here is the top one :)

Valid Well-formed HTML

眼角的笑意。2024-10-02 20:16:07

尝试在 erb 模板中使用 h() 转义函数进行清理。那应该可以解决问题

Try using the h() escape function in your erb templates to sanitize. That should do the trick

薄情伤2024-10-02 20:16:07

查看 Loofah,一个基于 Nokogiri 的 HTML 清理库。这还将删除可能不安全的 HTML,这些 HTML 可能会在页面上注入恶意脚本或嵌入对象。您还应该清除样式块,这可能会弄乱页面上的标记。

Check out Loofah, an HTML sanitization library based on Nokogiri. This will also remove potentially unsafe HTML that could inject malicious script or embed objects on the page. You should also scrub out style blocks, which might mess up the markup on the page.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文