Maintain Markup Format with Highlight.js

1.3k views Asked by At

I am attempting to display dynamically generated HTML on my web page and do highlighting/formatting using highlight.js. I have the highlighting working correctly, however the indentation is not correct. Here's the jsFiddle.

The code shows like this: <div class="parent">parentContent<div class="child">childContent</div><div class="child">childContent</div><div class="child">childContent</div></div>

whereas I'd like to show up as it would in an IDE:

<div class="parent">
    parentContent
   <div class="child">
       childContent
   </div>
   <div class="child">
       childContent
   </div>
   <div class="child">
       childContent
   </div>
</div>

I understand it's called highlight.js not format.js :) but I thought it was possible and I haven't had much luck getting an answer from the API. I have tried configuring line breaks via hljs.configure({ useBR: true }); and the fixMarkup('value') looked promising but I have not implemented it with any success.

1

There are 1 answers

2
dgrundel On BEST ANSWER

Hear me out. I know this might seem kludgey, but you can put your html together as a string, like so:

for ( var i = 0; i < 3; i++){
    var html = '<div class="parent">' +
        '\n\tparentContent';

    for ( var j = 0; j < 3; j++){
        html += '\n\t<div class="child">childContent</div>';
    }

    html += '\n</div>\n'

    $('.grid-container')[0].innerHTML += html;
}

This gives you full control of the white space. It's also probably faster because you're not appending to the DOM several times, just once. You only trigger a redraw one time when you set the innerHTML of .grid-container.

JSFiddle here: https://jsfiddle.net/dgrundel/fjLwa592/1/