Sunday, August 14, 2011

Syntax Highlighter for Blogger

When I first started this blog I knew I'd be posting code snippets.  I think most developers will agree that code is much nicer to look at if it is highlighted nicely. There are dozens of articles out there that tell you how to do this, and I tried a few of them. But they just didn't look right, lines were overlapping, numbers were lined up correct, etc. I realized that one of the top pages from a Google search was from 2009.  The API that he refers to has evolved since.

The library of javascript and CSS written by Alex Gorbatchev, called SyntaxHighlighter. The version released as I'm writing this is 3.0.83.

The first thing to do is include the Javascript and CSS on your page. In your control panel, go to Design > Edit HTML. I put the lines to load the CSS and javascript code below the <title><data:blog.pageTitle/></title> element.







Note that I load Python and Ruby scripts by default, but you'll want to change that to whatever language you want to post code for. You can find the list of supported languages here. If you don't always post code snippets and don't want to load these files on every page of your blog, you can also include the script and link tags in the body of your blog post.

The last thing to do is to make sure that javascript gets invoked on your code. I added this right above </body> in the HTML template.

I put my code in in a <pre /> element. To configure an element for a certain language, use the class attribute. For example:
<pre class="brush: php">
echo "Hello World";
</pre>
There are many other configuration options, see Alex's website for more information.

No comments:

Post a Comment