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.