Search code examples
htmlpretty-print

prettify.js not highlighting my code


I was trying to use prettify.js to higlight my html code. Here is my html code

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Making Quines Prettier</title>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?autoload=true&amp;skin=sunburst&amp;lang=HTML" defer="defer"></script>
<style>.operative { font-weight: bold; border:1px solid yellow }</style>
</head>

<body>
<!-- Language hints can be put in XML application directive style comments. -->

<pre class="prettyprint">
<h1>Making Quines Prettier</h1>
<h1>Making Quines Prettier</h1>
</pre>

</body>
</html>

What I am expecting it just show

<h1>Making Quines Prettier</h1>
<h1>Making Quines Prettier</h1>

but its rendering HTML code and displaying output as:

Making Quines Prettier

Making Quines Prettier


Solution

  • you need to escape the content so that they are not rendered as html tags

    so the code would be written as

    <pre class="prettyprint">
        &lt;h1&gt;Making Quines Prettier&lt;/h1&gt;
        &lt;h1&gt;Making Quines Prettier&lt;/h1&gt;
    </pre>
    

    See the example here: http://jsfiddle.net/s1ckfbsj/1/

    EDIT

    If you really want to write html and have it rendered, here's an option:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
    <pre class="prettyprint">
        <h1>Making Quines Prettier</h1>
        <h1>Making Quines Prettier</h1>
    </pre>
    
    <script>
        $(function() {
            $('.prettyprint').each(function() {
                var $self = $(this);
                var html = $self.html();
                $self.text(html);
            });
        });
    </script>
    

    See the second example here: http://jsfiddle.net/s1ckfbsj/2/