cardamom cardamom - 1 year ago 92
jQuery Question

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


...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
in between those tags?

The main reference for this library is here.

Answer Source

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:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download