Add Syntax Highlighter to Blogger

There are quite few good Syntax Highlighters out there, one of them is “Prettify” which is simple and lightweight. Prettify states that it can automatically guess and highlight code snippets for many languages (best on C-like and HTML-like) and also has many language extensions, if you need one. So I setup a simple demo to test it and the result was quite good.

Syntax Highlighter

Demo

Simple setup

Adding Prettify Syntax Highlighter to any CMS or webpage is very easy. For Blogger you just need to go to your blog’s Template tab, click “Edit HTML” button and add the below script before </body> tag.

<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>

As you can see that the project is hosted on Google Code. This is an auto-loader which will automatically load the required JavaScript API and the CSS file from the subfolders of SVN. So the last thing that you are left is to mention where it should highlight the codes by adding class="prettyprint" to pre and/or code tags within Blogger Post Editor, HTML view. Here is an example:

<pre class="prettyprint">
$(function() {
 alert('I am using Prettify as Syntax Highlighter');
});
</pre>

There are also some styles available that you can call and load the stylesheet in one URL, here is an example:

<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?skin=desert"></script>

Own hosting

Well, the above tutorial was the simple yet effective setup but what if you want to host Prettify on your own server? Blogger don’t allow us to host files directly, so if you have got a hosting service then it’s good, otherwise you can use Google Code to upload the syntax highlighter files.

Download the file form this page, extract it using archive software like WinRAR or 7-Zip and upload “prettify.css” and “prettify.js” files by creating a project. Now same as above add the CSS file before </head> and the script before </body> tag respectively. To execute it you need to add prettyPrint(); before closing body tag as shown below:

<html>
<head>
{All head contents}

<b:skin><![CDATA[
{Inline CSS}
]]></b:skin>
<link href="https://example.googlecode.com/.../svn/prettify.css" type="text/css" rel="stylesheet" />
{Other JavaScript}
</head>
<body>
{Header, Footer, DIVs}

<script src="https://example.googlecode.com/.../svn/prettify.js"/>
<script>prettyPrint();</script>
</body>
</html>

It is not mandatory to add the external CSS file but instead you can add inline CSS before ]]><b:skin> to highlight the syntaxes with some style.

Find more about it on:

Updated on 2013-3-7

Popular posts from this blog

How to Resize Blogger Header to Logo Size

Create your own Contact Form with Kontactr for Blogger

Add Google Website Translator to Blogger