Add code highlighter to Blogger (Blogspot)

If you maintain a blog related to programming languages, you most definetly provide example code. Adding syntax highlighting to your code makes it more readable and easier to understand. In this post you will learn how to add a code highlighter to your blog on Blogger (blogspot.com).

Before we start we have to choose a code hightlighter library. We have to choose a highlighting library that does highlighting in the browser and hosted on some the server. Because Blogger does not allow custom plugins that does processing (on the server side) and does not allow uploading javascript files.

Here is a list of popular syntax highlighters:

  • Google Code Prettify - Developed and used by Google Code project. Lightweight, hosted on the Google server and used on this blog.

  • SyntaxHighlighter - Probably the most popular and feature rich highlighter. Used by Apache, Mozilla, Yahoo!. You can find links to hosted versions.

  • Highlight.js - Lightweight, themable highlighter.

First, you have to choose library to use. This blog uses lightweight "Google Code Prettify", so I will be using the it in the exmaples below. But the process of adding it to your blog is the same for any other library. Once you made a choice, find a hosted file for that library.

Here is a link to the file from Google Code Project page:

http://google-code-prettify.googlecode.com/svn/loader/run_prettify.js

<!-- Also hosts file on secure connection -->
https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js

Add highlighter to Blogger

In order to add the hightlighter to your blog, follow this step:

  1. Login to your account

  2. Navigate to: Your blog » Template » Edit HTML

  3. Just before the closing </body> tag add this code

    <script src='http://google-code-prettify.googlecode.com/svn/loader/run_prettify.js'/>
    <script type='text/javascript'>prettyPrint();</script>
    </body>
  4. Click on "Save Template"

  5. Done

NOTE:
Do not forget to backup your template before making any changes.

You have successfully added Google Code Prettify syntax highlighter to your blog. Now in order to highlight your code wrap it into <pre class="prettyprint">...</pre> or <code class="prettyprint">...</code> tags.

Example

Here is an example of Code highlighter in use.

function JavascriptFunction() {
    // Comment example
    var myVariable;

    var privateMethod = function(){ };

    return myVariable;
}

// jQuery code sample
$.extend({ 
    myNamespaced: function(myArg){ 
        return 'namespaced.' + myArg; 
    } 
}); 
$.myNamespaced('A'); // Another comment