Highlightjs with html code

How do I put my HTML so that highlight.js turns it off?

I tried

<pre>
    <code>
        <!-- HTML Prettify -->
        <div>
            <pre class="pre-code-ception"><code> haha </code></pre>
        </div>
    </code>
</pre>

I put at the end of my file:

<script type="text/javascript">
    hljs.initHighlightingOnLoad();
</script>

But everything is displayed as plain HTML.

+4
source share
4 answers

Oh, I think I understand the problem. You need to avoid HTML in the element <code>, otherwise it will be interpreted as HTML instead of text (you want the HTML to be displayed literally, and not be interpreted as part of the structure of the web page).

< &lt; > &gt;, HTML . ( " ", , HTML .)

+13

user2932428 jQuery:

document.querySelectorAll("code").forEach(function(element) {
    element.innerHTML = element.innerHTML.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
});
+2

@Cameron html:

, , , , , heredoc htmlspecialchars() (PHP), . Heredoc .

echo <pre><code>...</code></pre>.

, .

:

<?php

$code = <<< EOT

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>

    <body>

        <img src="image.png" />

    </body>
</html>

EOT;

?>

<pre>
    <code class="html">
        <?php echo htmlspecialchars( $code ); ?>
    </code>
</pre>

One note about using heredoc is that your closure EOTshould be completely left aligned.

+1
source

you need to avoid the contents in <code class="html">

$('code').each(function() {
  var that = $(this);
  // cache the content of 'code'
  var html = that.html().trim();
  that.empty();
  // escape the content
  that.text(html);
});
hljs.initHighlightingOnLoad();
+1
source

Source: https://habr.com/ru/post/1529260/


All Articles