Rendering safe html in Rails 3



我有一个数据库,里面装满了我试图迁移到Rails的旧博客文章。正文字段由看起来格式类似的帖子组成:

Paragraph text paragraph text paragraph text and even more paragraph text. Paragraph text paragraph text paragraph text and even more paragraph text. Paragraph text paragraph text paragraph text and even more paragraph text. Paragraph text paragraph text paragraph text and even more paragraph text.
<iframe src="http://www.youtube.com?v=XXXXXXXX" width="400" height="250"></iframe>
Paragraph text paragraph text paragraph text and even more paragraph text. Paragraph text paragraph text paragraph text and even more paragraph text. Paragraph text paragraph text paragraph text and even more paragraph text. Paragraph text paragraph text paragraph text and even more paragraph text.
<ul>
<li>List item</li>
<li>List item</li>
<li>List item</li>
<li>List item</li>
</ul>
Paragraph text paragraph text paragraph text and even more paragraph text. Paragraph text paragraph text paragraph text and even more paragraph text. Paragraph text paragraph text paragraph text and even more paragraph text. Paragraph text paragraph text paragraph text and even more paragraph text.

因此,我要做的是将段落文本包装在<p>中,但不使用其他html元素。以下是我尝试过的:

simple_format(@post.body)=这将<p>放在所有内容的周围,但也会用每个列表项之间的分隔符污染我的无序列表。此外,iframe嵌入不会显示。

raw(@post.body)@post.boxy.html_safe=iframe嵌入列表和无序列表显示得很好,但所有内容都在一起运行,因为无法替换新行。

simple_format(@post.body,{},{:消毒=>false})=酷。现在我可以看到所有的html标签了!根本不起作用

@post.body.gsub(/\r\n?/,"<br/>").html_safe=与simple_format的问题相同。。。我在我的html块元素标记中得到了换行符。

关于如何做到这一点,有什么建议吗?

我想你在上一个例子中几乎已经做到了,但我的猜测是你需要在前面做.html_safe:

@post.body.html_safe.gsub(/rn?/,"<br/>") 

我认为你的问题与其说是与rails有关,不如说是试图修复损坏的html。在任何情况下,您的示例都建议应该包装在<p>标记中的文本是尚未以标记开头的行。只有你知道这个规则是否适用于其他帖子。

试试这个。它还解释了前导空格。

raw( @post.body.gsub(/^s*[^<].*/, '<p>&</p>') )

如果以上内容太脆弱,我建议使用Nokogiri。这将获取每个顶级连续文本块,并将其封装在<p>:中

doc = Nokogiri.XML("<body>n" + @post.body + "n</body>n")
doc.root.children.each{|c| c.text? and c.replace("<p>#{c.to_s.strip}</p>") }
raw( doc.root.inner_html )

要在文本块的换行处插入<br>,可以将上面的c.to_s.strip替换为c.to_s.strip.gsub(/r?n/, "<br/>n")

我注意到你的问题有/rn?/。你有没有期待过旧的Mac OS支架(r)自己回来?如果你想处理Windows或Unix,你应该使用/r?n/

我认为sanitize可能是您想要的

%= sanitize @article.body %>

def sanitize(html, options = {})
  self.class.white_list_sanitizer.sanitize(html, options).try(:html_safe)
end

最新更新