Search code examples
javascriptjqueryfrontendsyntax-highlightinghighlight.js

Import and syntax highlight code from external source


I'm not a front-end developer and have been struggling for hours to get highlight.js to do what I want. Need to display code nicely in a blog. Okay, it works perfectly in that it renders the code I post into

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

...very nicely and colourfully with the chosen style, idea.css for example. I've got all the styles and highlight.pack.js ready to go in the directory.

But it is so messy to paste the whole program between those tags! It is more cleanly reusable for other things if the code can stay in its file.

What is the shortest and most elegant way (without loading in any external libraries if possible) to get it to pull the code out of a python file in the same directory myCode.py in between those tags?

The main reference for this library is here.


Solution

  • I am assuming that your code file to highlight lives on the webserver.

    1. Import the file using JQuery get.
    2. Put the content into the code tags.
    3. Call the appropriate function from hightlight.js to make it highlight the code.

    Here is some HTML/JS code:

    <pre><code></code></pre>
    <script type="text/javascript">
      $.get("/myCode.py", function(response) {  //(1)
        $("code").html(response);               //(2)
        $("code").each(function(i, block) {    
        hljs.highlightBlock(block);             //(3)
        });
    });
    </script>
    

    Note that this assumes that there is only one <code> tag in your page.Otherwise step 2 needs to be adjusted.