Nav links

Saturday, 11 February 2017

Use Prism syntax highlighter with Blogger Dynamic Views

For years I've been putting off setting up a good syntax highlighter for this blog, but with my recent large code utterances I could delay no longer. After a brief review of the available syntax highlighting offerings I settled on Prism. However, getting it to work on Blogger turned out to be a little trickier than anticipated.

After following the Prism basic installation instructions, and reviewing the two Blogger Prism tutorials linked from the Prism site, I still had no highlighting visible. I had an inkling that its failure was due to the use of Dynamic Templates, where the actual content of the blog is loaded after the rest of the page. That is, the syntax highlighter does its work when the page has loaded, but this is before the content to highlight has been fetched. Searching further, I found a blog detailing How To Re-Run Prism.js On AJAX Content, after which I was able to confirm that the highlighting was working when I ran the following command from a Javascript console after the content had been retrieved:
Prism.highlightAll();
I just needed to work out how to get the page to automatically run this command at the appropriate time. This led to a Stack Overflow answer, which is about using a different syntax highlighter, Google Code Prettify but applies to Prism too. Following this, I added to my blog template, just before the closing head tag:

    <script>
        $(window.blogger.ui()).on('viewitem', function (event, post, element) {
            Prism.highlightAll();
        });
    </script>

The syntax highlighting now works perfectly.