I recently changed this blog's theme to a Dynamic Views theme. Its looks and behaviour are much more modern now. However, syntax highlightling for my source code snippets didn't work anymore. Apparently my previous solution with highlight.js doesn't work well with Dynamic Views. (For the "classic" themes it still works, though.)

I tried modifying the theme's HTML and inserted the required tags in the header section, but I just couldn't get it to work. Maybe it has to do with the fact that posts are now loaded after the main page has loaded. I tried inserting the tags at the start of a post, but that didn't seem to work either. Searching for an alternative, I stumbled upon Google's code prettifier. It looked super easy to set up, so I gave it a try and it works well. Here's how to make it work:

  1. Edit the post where source code syntax highlighting should be applied.
  2. In the post editor, click HTML to enable HTML source editing.
  3. At the first line of the post, insert this:
    <script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script>
  4. Surround code snippets with <pre class="prettyprint"> and </pre> (code instead of pre works too), like in this example for HTML code - notice the &lt; instead of < to prevent parsing issues:
    <pre class="prettyprint">
    &lt;input type="Submit" value="Submit" />
    </pre>
    to get this in the resulting post:
    <input type="Submit" value="Submit" />
  5. to get a horizontal scrollbar if the source code lines are too long to fit, edit the theme's CSS. In the left menu, click Theme, then click Customize under "Live on blog", then click Advanced and then Add CSS. Add the following CSS:
    pre, code {
      overflow-x: auto;
    }

    Click Apply to blog (top right) to save the CSS.

The main disadvantage compared to the old solution is that now I have to include that script tag at the start of every blog post (again, inserting it in the header of the template's HTML didn't work). I can make that easier by adding it to the post template so that it gets inserted automatically:

However, it still gets included in every post and as a consequence it's loaded several times. The browser is smart enough to notice that it has already loaded it, so it doesn't actually fetch it from the source website again, but the JavaScript code is still interpreted every time. So it works, but it's not an optimal solution. If you know a better one, please let me know.

Update 5 Feb 2021: This blog is no longer on Blogger; it's on GitHub now and has been migrated to Jekyll, where syntax highlighting is a built-in feature.