Saturday, November 02, 2019

Formatting Code on Blogs...

Finally found at how to do this using prism.js from the excellent blog post here.

This is done by adding a link to the CSS in <head>, and a link to the JS before closing the <body> tag. The theme is specified with the css name, e.g. prism.min.css or prism-tomrrow.min.css. For Blogger, this has to be done by updating the Blog Theme.

<head>
  ...
  <link
    href='https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/themes/prism-tomorrow.min.css' 
    rel='stylesheet'/>
</head>
<body>
  ...
  <script
    src='https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/prism.min.js'/>
  <script
    src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/plugins/autoloader/prism-autoloader.min.js"/>
</body>

There is a full list of the CDN files here, and a full list of supported languages here.

Code is enclosed within the <pre> tag to preserve formatting; and within the <code> tags, also specifying the language for highlighting:

<pre><code class="language-java">   class App {
      public static void main(String[] args) {
         System.out.println("Hello World!");
      }
   }
</code></pre>

Formatting can also be done inline.

Note that to display HTML or PHP some of the symbols will need to be escaped so the browser doesn't try to parse the code. An online converter like Free Online HTML Escape Tool can do this.