Search This Blog

Adding syntax highlighted code to your Blogger posts

posted on Friday, March 2, 2012

Update: it seems the website of the SyntaxHighlighter no longer exts.

One very useful thing when trying to write a blog about development and other geeky stuff is to display code... . Unfortunatly, as far is I know, Blogger does not have a -decent- feature for this. You can add code using <code>-tags, but I prefer syntax high-lighting since it makes code much more readable.

That's where the JavaScript library SyntaxHiglighter comes in!

The easiest way to install this is to implement it directly in your Blogger template, so it's always there when you need it.
  • Go to the home page of your blog.
  • Click "Template" and find the link "Edit HTML".
  • You'll be given a warning that this can be tricky, so you might want to save the current template first.
  • In the HTML code, look for the </head>-tag and add the code below, right above the </head>-tag.
  • Save and close the template.
  • Create a new blog post and use <pre>-tags to add code, as you can see in the code below.

Script to add to your template:
These are 'brushes', syntaxes for different coding languages. Obviously, you can leave out the brushes for the languages you don't speak :)

Tags to add code to your blog post:
alert("Hello, world!");
When you hit Save/Publish/Preview you should now see some very cool syntax high-lighted code!

One more thing!
My first response to seeing the final result was: "where's my 'copy-to-clipboard'-option?". So, if you're wondering about the same thing: it's in there, you just need to know how to find it :) Just double-click the code and it will be selected without line numbers and in a structured format. Ctrl + C and you're set!

That's it for today's useful features :)

I've added this list of which brushes fit with which syntax as a useful reference.

Credit to whom credit is due:
The SyntaxHighlighter website: (link intentionally broken as this website seems to no longer exist)
This also has extra info about configuration, the available brushes, themes for the code view, ... .

Update 01/11/2012
I recently noticed an issue with the syntax highlighter that only seems to occur in the latest version in Chome, you can find a fix for this issue here:

Could be useful, right?

No comments:

Post a Comment