Anki: add syntax highlighting with javascript (highlight.js)

Tested on Anki 2.1.44 desktop version, however, I could not make it work for Ankidroid.

Go to highlightjs.org and download a custom package. copy and paste the files highlight.min.js and xxxxx.min.css into the Anki folder: /collection.media/. This folder is usually located around:

Create a file my_highlight.js and paste the following code inside:

document.querySelectorAll('pre code').forEach((block) => {
    hljs.highlightBlock(block);
});

Move this file into your /collection.media/ folder as well. Now, go to the menu "Tools" -> "Note Types" and select the note type you'd like to use for syntax highlighting. Click on that type and the button"Cards...".

Choose "front template" radio button and paste the following:

{{Front}}
<link rel="stylesheet" href="xxxxx.min.css">


<script>
    if (typeof hljs === "undefined") {
        var script = document.createElement('script');
        script.src = "highlight.min.js";
        script.async = false;
        document.head.appendChild(script);
    }

    var script = document.createElement('script');
    script.src = 'my_highlight.js';
    script.async = false;
    document.head.appendChild(script);
    document.head.removeChild(script);
</script>

<script>hljs.highlightAll();</script>

Now if everything went according to plan you can now create a card and open the "edit html" window add:

<pre><code class="language-cpp"> some code </pre><code>

to see some syntax highlighting!

Reference

reddit thread

No comments

All html tags except <b> and <i> will be removed from your comment. You can make links by just typing the url or mail-address.
Anti-spam question: