Display Python code on a webpage using highlight.js and jquery

2.7k Views Asked by At

Given this html fragment

<div class="row">
    <div class="col-md-12">
        <pre><code id="sourcecode" class="python">print "Hello World"</code></pre>
    </div>
</div>

I try to change the actual displayed code on the fly, e.g.:

$.ajax({
    type: 'GET',
    url: '/api/1/strategy/source/json/{{ name }}',
    dataType: "json",
    success: function (response) {
        console.log(response);
        $("#sourcecode").textContent = response;
    }
})

Unfortunately it doesn't work. Any hints for me? (in the console log I see the correct response)

Thomas

1

There are 1 best solutions below

0
On

Have a look into the below example, specifically the success function inside your $.ajax function.

As long as the response is valid HTML, the h1js code should be working.


<head>

  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/styles/default.min.css">
  <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/highlight.min.js"></script>

</head>

<body>

  <div class="row">
    <div class="col-md-12">
      <pre><code id="sourcecode" class="python">print "Hello World"</code></pre>
    </div>
  </div>

  <script>
    hljs.initHighlightingOnLoad();

    $(function() {
      $.ajax({
        type: 'GET',
        url: '/api/1/strategy/source/json/{{ name }}',
        dataType: "json",

        success: function (response) {
          console.log(response);
          $("#sourcecode").html(response);
          $('pre code').each(function(i, block) {
            hljs.highlightBlock(block);
          });
        }
      });
    });
  </script>

</body>