Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing Nokogiri from escaping characters?

I have created a text node and inserted into my document like so:

#<Nokogiri::XML::Text:0x3fcce081481c "<%= stylesheet_link_tag 'style'%>">]>

When I try to save the document with this:

File.open('ng.html', 'w+'){|f| f << page.to_html}

I get this in the actual document:

&lt;%= stylesheet_link_tag 'style'%&gt;

Is there a way to disable the escaping and save my page with my erb tags intact?

Thanks!

like image 594
mikewilliamson Avatar asked Jul 15 '10 03:07

mikewilliamson


2 Answers

Perhaps you want to use the "<<" method to insert raw XML like this:

builder = Nokogiri::XML::Builder.new do |b|
  b.html do
    b.head do
      b << stylesheet_link_tag 'style'
    end
  end
end
builder.to_xml
like image 72
Head Avatar answered Sep 22 '22 12:09

Head


You are obliged to escape some characters in text elements like:

"   &quot;
'   &apos;
<   &lt;
>   &gt;
&   &amp;

If you want your text verbatim use a CDATA section since everything inside a CDATA section is ignored by the parser.

Nokogiri example:

builder = Nokogiri::HTML::Builder.new do |b|
  b.html do
    b.head do
      b.cdata "<%= stylesheet_link_tag 'style'%>"
   end
  end
end
builder.to_html

This should keep you erb tags intact!

like image 44
fotos Avatar answered Sep 20 '22 12:09

fotos