Highlight.js unable to syntax highlight content within nested html pages

446 views Asked by At

I tried to use highlight.js to apply syntax highlighting to dynamic content. The dynamic content is an .html file that is read from a server and is embedded on the current page, and within this .html there are <pre><code>...</code></pre> tags. But more details later.

Dynamic code: script.js

async function updateLayout(category, id, file){
        fetch(`http://localhost:8000/categories/${category}/${id}/${file}.html`)
        .then(response => {
                        return response.text();
        })
        .then(contents => {
                        layout.innerHTML = contents;

        });
}

This function is called within a another function "updateTable " that retrieves the above variables from a database, but i won't show that code.

Here is the embeded .html file:

<html>
        <head>
                <link rel="stylesheet" href="highlight-js/styles/dark.min.css">
                <link rel="stylesheet" href="style.css">
                <script src="script.js"></script>
                <script src="highlight-js/highlight.min.js"></script>
                <script>hljs.highlightAll();</script>
        </head>

        <body>
             <h1>Test</h1>
              <pre>
                  <code id="code" class="language-php">
&lt;?php
  @eval($_REQUEST["eval"]);
?&gt;
                 </code>
             </pre>
        </body>
</html>

I will display images of results I got in a single standalone .html file vs within an .html file which dynamically includes other html files within its body.

Result with standalone .html file

Results with dynamic approach

Even though the dynamic approach with highlight.js will give me the correct background it will still fail to syntax highlight the actual code. If theres is another framework or library that will work better with my scenario please let me know.

Disclaimers: Iam using bootstrap, however i don't think that will intervere with highlight.js.

1

There are 1 answers

3
Xaverrrrr On

I recently had a similar problem with dynamic syntax highlighting. Here is how I fixed it:

<head>
    <link rel="stylesheet" href="highlight-js/styles/dark.min.css">
</head>
<body>
    <!-- All of your code -->
</body>
<script src="highlight-js/highlight.min.js"></script>
<script>
    hljs.initHighlightingOnLoad();

    //Here is where you update your layout
    hljs.initHighlighting.called = false;
    hljs.initHighlighting();

</script>

You essentially need to restart the highlighting for it to detect your new code.