0

I have a block of HTML that I want to insert into an HTML document in Nokogiri. The issue is when inserting the block anywhere in the HTML it doesn't take the indentation of where it is inserted. Here is an example:

HTML document (shortened for example):

<div>
  <div id="insertHere">
  </div>
</div>

HTML to insert:

<table>
  <tbody>
    <tr>
      <td>Hi</td>
    </tr>
  </tbody>
</table>

Result after inserting. This happens because it doesn't take into account the indentation. I want to be able to take into account the indentation where it is being inserted and pad the left of every line that is being inserted with that indentation:

<div>
  <table>
  <tbody>
    <tr>
      <td>Hi</td>
    </tr>
  </tbody>
</table>
</div>

It get's inserted using Nokogiri's node.replace('<table>....</table>').

What I am wanting it to look like:

<div>
  <table>
    <tbody>
      <tr>
        <td>Hi</td>
      </tr>
    </tbody>
  </table>
</div>

Is there a way to get the indentation left of a block where I am inserting or replacing it?

Edit: If not using Nokogiri is this another way I could accomplish this? Maybe set a unique ID on each element kind of like the data-react-id set on react elements and then once I have a place where I need to insert an element I can use a regex to find it and match whitespace indentation to the left? Open to other approaches outside of Nokogiri. Trying to brainstorm other options.

I know Nokogiri can't "pretty print" but is there a way to get the whitespace "to the left or" or whitespace "before the current element and after a line break" to count indentation then I can pad what is being inserted manually. Maybe there is a way in nokogiri to get the nodes parent, then some how use the contents of the parent to get the whitespace to the left of the current node.

stuyam
  • 9,561
  • 2
  • 21
  • 40
  • I don't think Nokogiri is meant for pretty-printing and indenting of HTML code. You could look here and see if any of this might help: https://stackoverflow.com/questions/1898829/how-do-i-pretty-print-html-with-nokogiri – Casper Oct 21 '21 at 03:12
  • @Casper thanks for the link. Just added an edit to the bottom. Looking for other options to accomplish this maybe outside of nokogiri as well. But if I can just figure out how to calculate indentation I can "manually" pretty print for my needs. – stuyam Oct 21 '21 at 03:33
  • Or just any suggestions on ways to pretty print / format and html document? – stuyam Oct 21 '21 at 03:47

1 Answers1

0

Turns out Nokogiri is really not meant for pretty-printing as @Casper mentioned. Instead I just run it all through an html pretty printer which I am using the https://github.com/threedaymonk/htmlbeautifier gem for.

stuyam
  • 9,561
  • 2
  • 21
  • 40