Friday 2 March 2012

Formatting code on blogger using prettify

I want to post code snippets onto blogger, but plain text code is boring to look at.  Example:

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}

Doing a quick google search brought me to prettify (http://code.google.com/p/google-code-prettify).  It provides javascript and css files for formatting code on a web page.

On blogger you can edit the html and link to third party javascript/css files.  Here is how:

  • Log into blogger
  • Go to Template -> Edit Html
  • Read the warning and then click 'Proceed'
  • In the <head> section add the following:
<link href='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css' rel='stylesheet' type='text/css'/>
<script src='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js' type='text/javascript'/>

  • Then change the body tag to contain the following:
<body onload='prettyPrint()'>
  • Click save and now you are ready to use the <pre class="prettyprint"> </pre> tag.
Now in a post, click on the html tag and try out the tags. Example:
public class Hello {
  public static void main(String args[]) {
    System.out.println("Hello World!");
  }
}

No comments:

Post a Comment