Preventing Nokogiri from escaping characters?

烂漫一生 提交于 2019-11-30 04:49:20

问题


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!


回答1:


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!




回答2:


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


来源:https://stackoverflow.com/questions/3252330/preventing-nokogiri-from-escaping-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!