首页 > 解决方案 > 如何在不创建不需要的自定义标签的情况下使用 Nokogiri::HTML.fragment

问题描述

我有支持 Nokogiri 的 HTML 碎片的 Ruby 代码。

当用户"<"向应用程序输入文本时,Nokogiri::HTML.fragment将其添加到自定义 HTML 标记。

如果用户输入类似

"One <two three"

该应用程序将显示它像

"one <two three></two>"

我正在使用Nokogiri::HTML.fragment(html, encoding = 'UTF-8').

有谁知道如何修理它?

标签: htmlruby-on-railsrubynokogiri

解决方案


您不了解 HTML 与解析器的文本有何不同。Nokogiri 认为这one <two three是 HTML 并尝试对其进行验证,看到<two three并认为它是一个标记<two后跟一个参数,但没有看到结束>,因此它进行了一些修复以试图提供帮助。

require 'nokogiri'

doc = Nokogiri::HTML::DocumentFragment.parse('one <two three') 
doc.to_html # => "one <two three></two>"

相反,就像您想创建一个包含 的页面一样one <two three,您必须提供 HTML 编码文本:

doc = Nokogiri::HTML::DocumentFragment.parse('one &lt;two three') 
doc.to_html # => "one &lt;two three"

您可以使用 HTML Entities gem 自动执行此操作:

require 'htmlentities'
coder = HTMLEntities.new

doc = Nokogiri::HTML::fragment(coder.encode('one <two three'))
doc.to_html # => "one &lt;two three"

推荐阅读