【发布时间】:2019-10-30 04:19:28
【问题描述】:
我在 Rails 中使用 Nokogiri 来解析我的 HTML 并将自闭合标签转换为常规标签。这很好用,但它也转换了我们的模板标签 [% 和 %],例如:
html = "<a href='[% hello %]'>Hello from [% Us %]</a>"
Nokogiri::HTML::DocumentFragment.parse(html).to_html
将转换为:
<a href='%5B%%20hello%20%%5D'>Hello from [% Us %]</a>
转换后不使用gsub如何避免?
这没有帮助:
html = "<a href='[% hello %]'>Hello from [% Us %]</a>"
doc = Nokogiri::HTML::Document.new
doc.encoding = 'UTF-8'
doc.fragment(html).to_html
#=> "<a href=\"%5B%%20hello%20%%5D\">Hello from [% Us %]</a>"
【问题讨论】:
-
@anothermh 请参阅上面的更新。推荐的解决方案似乎没有帮助。也许是
.to_html?如果是这样,正确的方法是什么? -
赞成确定问题范围并提供可以轻松运行的测试代码????。您能否用预期的输出更新问题?
-
@Ben Try
doc.fragment(html).to_xml=>"<a href=\"[% hello %]\">Hello from [% Us %]</a>"。应该可以工作,因为它是 XML,而且 XML 不一定知道 HTML 实体。
标签: ruby-on-rails ruby nokogiri