ruby-on-railsrubynokogiri

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?


Solution

  • 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!