14 July 2017

Syntax Highlighter for Source Code on Blogs - Google's code-prettify

 A few months back, I started sharing my open source codes on my blog and was looking around to find the best means to highlight the code samples.  Sometimes it helps to have code on the blog for a more detailed  step by step  explanation rather than just post a link to the whole code on a github repo.
There are many tools out there which are suited for the task. I finally zeroed in on Google's code-prettify becos of the simplicity of the solution that it offers. 

As the documentation says, code-prettify is "An embeddable javascript that makes source-code snippets in HTML prettier."


This is the way to setup your blogger for using code-pretiffy :
Step 1:   Login to your blogger account , click on Theme -> Edit HTML


Step 2: Add the following code just below the html tag <head>  . By this You can load the JavaScript and CSS for prettify via one URL (check with prettify documentation of the latest/updated URL):
<script src=""https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js""></script>

The above code will load the entire system and schedule the prettifier to run on page load


Step 3: After adding the above code , save the theme.

Step 4: Next open the blog post in which  you want to highlight the source code. This can be opened in two modes - Compose and HTML.  Choose to open in HTML.

Step 5: Use the "pre"  tag and give it a class "prettyprint" , for highlighting our code as follows. This is shown below: 
<pre class="prettyprint lang-py">
your source code goes here
</pre>

Additional Options: 
  • If you want to highlight code written in C or Java, then you need to change "lang-py" to "lang-c" or "lang-java".
  • There are also other skins/themes  that can be used. More details are on the Gallery of Themes for code-prettify . 
  • There is also an additional option for line numbering .

No comments:

Post a Comment