简体   繁体   中英

How can I print HTML code with colors syntax highlighting on my HTML page?

I'm trying to converts my code snippets into pretty-printed HTML format with syntax highlighting.

            <xmp ng-non-bindable>
                <ul>
                    <li ng-repeat="list in lists" class="input">
                        {{list}}
                    </li>
                </ul>
            </xmp>

Result

在此处输入图片说明


I want to print out something like this

在此处输入图片说明


What is the best day to achieve something like that ?

Can someone please direct me to the right direction ?

I'd recommend using highlightjs as it supports a large number of languages and comes with many color themes. For HTML code specifically, you need to escape HTML tags. There're many tools online to help you in achieving that.

Here's a quick demo for that using highlighjs:

 <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.6/styles/darkula.min.css"> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.6/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad();</script> <pre><code class="hljs html"> &lt;ul&gt; &lt;li ng-repeat=&quot;list in lists&quot; class=&quot;input&quot;&gt; {{list}} &lt;/li&gt; &lt;/ul&gt; </code></pre>

To print your HTML tags,manually you need to replace the < with &lt; and > with &lgt;

So if your code is this,then you can print the tags.

  &lt;xmp ng-non-bindable&gt;<br />
                &lt;ul&gt;<br />
                    &lt;li ng-repeat=&quot;list in lists&quot; class=&quot;input&quot;&gt;<br />
                        {{list}}<br />
                    &lt;/li&gt;<br />
                &lt;/ul&gt;<br />
            &lt;/xmp&gt;

A better way would be to use the following and Try this Syntax highlighter link

you could use a function to programatically escape the html content.

function escapeHTML(htmlStr) {
  return htmlStr.split("<").join("&lt;").split(">").join("&gt;");
}

Also you could store the content of the snippet in a file, fetch it and inject it programatically with JS:

// fetch the file to get its content as string
fetch("full/path/to/file")
  .then(response => response.text()) // process response
  .then(text => {
    // escape HTML
    const escapedHTML = escapeHTML(text);
    
    // get target DOM element (code element)
    // and inject snippet content
    const snippetEl = document.querySelector("#mySnippet")
    snippetEl.innerHTML = escapedHTML;
    
    // reapply highlighting
    hljs.highlightBlock(snippetEl);
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM