Today we will learn how to add syntax highlighter to Blogger. I will go with Google Prettify as adding it to Blogger (or any other CMS) is simple and easy.

So at first you have to download the script file from Google Prettify (reference also). Extract it using archive software like WinRAR or 7-Zip. Now within the extracted folder find for prettify.js and prettify.css files and upload these to your hosting service.
Step 1: Blogger don’t allow us to host files directly so if you have got a hosting service then its good, otherwise you can use Google code to host prettify for you. Go to code.google.com/hosting/createProject, login using your Google ID, create a project and upload your files. If you are too lazy then you can use the below script sources from the project itself.
Step 2: Go to Blogger’s dashboard > Template > Edit HTML and add the syntax highlighter script before closing </body> tag.
<script src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js"></script>
Step 3: You need to add the CSS file. You can add it directly just before ]]></b:skin> by viewing the raw data from the downloaded file or from the project, or you can add your hosted file or from the project (as shown below) just after ]]></b:skin>
<link rel="stylesheet" href=" http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css"/>
If you need more styles then you can get the style sheets form prettify themes gallery.
Step 4: Add prettyPrint() to call and execute it. As suggested in the documentation, you can add onload='prettyPrint()' to your opening body tag like the example below:
<body onload="prettyPrint()">Or you can add it just before closing body tag as the example below (reference: Syntax Highlighting to any project - Nettuts+):
<script src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js"></script>
<script>prettyPrint();</script>
</body>Use any one of the methods in step 4. If you think that the onload method is blocking your page (like I did with my AdSense ads) use the second method. It works perfectly.
Step 5: It is the last step. The syntax highlighter will search either for pre or code tags with a class prettyprint. So whenever you are writing/posting codes or snippets, format it like this:
<pre class="prettyprint">
$(document).ready(function() {
alert('I am using Prettify as Syntax Highlighter');
});
</pre>Note: Projects hosted on Google Codes are open source and the owners have some rights to add a license to it. However, I didn’t find any documentation that is not permitting to use the direct sources from the Prettify Syntax Highlighter project but it will be best if you host it elsewhere so that if the direct links changes or gets deleted, it won’t affect you.
1 Comment:
Raju,
You have some awesome tips there! Mighty useful for bloggers like me. Thanks! :)
Post a Comment