Wednesday, November 21, 2012

Using SyntaxHighlighter in Blogger

I have been postponing posting code here since I wanted it to be formatted properly and did not have a chance to play with syntax highlighting. There is a nice library that contains css styles and formatting scripts, named just that; here is the site.

To get the highlighter to work, you need to add some script and styles to your blog template. There are nice folks out there who did this work already, you can find one here.

This particular guide and many others tell you to embed the links into the page along with a script tag that enforces the highlighting when the page is loaded. Here is the suggested script snippet that is used in addition to links to CSS and Javascript files.
<script language="javascript" type="text/javascript">
 SyntaxHighlighter.config.bloggerMode = true;

Unfortunately for dynamic view templates like this one on Blogger, it does not work. There is a workaround though, that is to call the highlighter when the page is loaded. The code below highlights anything that has the right class attribute for SyntaxHighlighter library, independent of the name attribute. Which makes it nicer when you have multiple code snippets on a page.
<script type="text/javascript">
  // code snippet is loaded here, highlight everything.
  SyntaxHighlighter.config.bloggerMode = true;

You don't even have to add this to your template. Just make sure you add it to the bottom of your post using the HTML view on Blogger (not the Compose view). As you can see here, it works. It took me some time to discover that the dynamic views are rendered differently. Most instructions before that were irrelevant. Hope you stumble into this note faster than it took me to find this information.

No comments:

Post a Comment