Tuesday, August 31, 2010

How to Pretty-Print Code Snippets in Blogger

I often want to include snippets of code in my instructional blog posts, so to make my blog posts easier to read, I decided to add syntax-highlighting to my blog tonight. There are various syntax highlighting solutions out there, but we use google-code-prettify on code.google.com and it's worked well enough there, so I went with what I knew.

Here's how I added it to my Blogger blog:

  1. Click the Design tab and "Edit HTML".
  2. After the meta tab in the HTML, paste these two includes for the JS and CSS:
    <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'/>
    
  3. Search for script - for me, there's a script tag near the bottom of the page. In that script tag, put this javascript call:
    prettyPrint();
    
    If that tag doesn't exist, then just create a script tag at the bottom yourself.
  4. Now, whenever you're posting, add the prettyprint class to your pre or code tags:
    <pre class="prettyprint">
    var i = 2 + 4;
    </pre>
    

To see examples of where I've used this, check out JSON API for Posterous for Python snippets or the Google APIs Timeline for JS snippets.

For more details on using the prettify library, see the readme.

No comments: