How to use [% special characters in Nokogiri

Viewed 300

I am using Nokogiri in Rails to parse my HTML and convert self-closing tags to regular ones. That works great, but it also converts our template tags which are [% and %], so for example:

html = "<a href='[% hello %]'>Hello from [% Us %]</a>"
Nokogiri::HTML::DocumentFragment.parse(html).to_html

will convert to:

<a href='%5B%%20hello%20%%5D'>Hello from [% Us %]</a>

How do I avoid it without using gsub after the conversion?

This did not help:

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>" 
1 Answers

@anothermh actually answered my question (see comments below my question). I ended up using his suggestion (to_xml)

However, I needed more out of the parsing of my code than I decided not to mention. I needed to be able to keep the special characters in the tags, but also convert self-closing tags to regular tags.

My solution was to use the XHTML format, described here: https://www.rubydoc.info/github/sparklemotion/nokogiri/Nokogiri/XML/Node/SaveOptions#FORMAT-constant

html = "... my html ..."    
doc = Nokogiri::HTML::Document.new
doc.encoding = 'UTF-8'
final = doc.parse(html).to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::DEFAULT_XHTML)
Related