How to add syntax highlighter on Blogger

This solution is helpful in prettifying code blocks we share on our posts. Usually I'll just add custom CSS to the <pre> tag to improve the look and feel of the pre container, but that's as far as I can get. So you could imagine how nicer it would be to apply an actual syntax highlighter on our posts!

Many thanks to Alex Gorbatchev for creating this syntax highlighter, and this site for documenting a step by step post on how to apply it on Blogger. Here's my own version of the guide and a usage demo as well so I know where to check when I forget about it! Setting it up:

Open Blogger's HTML editor and paste the following before the </head> tag:


//Core script




Save it. Now it's ready to use :)

Themes

Notice the highlighted line above (line 7), there are many themes you can use, in this blog I'm using the Default theme. You can find all available themes here.

How to use it?

Simply surround your code in a <pre> tag with a custom class:

PLACE YOUR CODE HERE

Notice the class attribute. "brush:html" says we're using the HTML syntax highlighter. Learn the different syntaxes you can use here. I guess what I'll be using most often is html, js, css, vb, and c. Simply replace the alias with the syntax of your choice. As long as it's supported, it's gonna look fine.

Demo (HTML, JS, CSS, VB, C):

HTML

Hello World


Javascript
function alertMsg(){
window.alert("Hello world!");
}

CSS
body {
background: #000000;
font-size: 12px;
position: absolute;
}

Visual Basic
Public Module mod
Sub Main()
Console.WriteLine ("Hello world!")
End Sub
End Module

C
#include 
int main()
{
printf("Hello, World!");
return 0;
}

Looks nice. :)

Finally

While it's definitely a neat way to display code on Blogger, it's not a convenient solution.

First, you have to insert the pre markup using the HTML editor instead of the Compose editor. That alone makes it troublesome, but heck inserting any type of code makes the HTML view mandatory so it can't be helped. Second, if you notice, it doesn't follow any indentation. That's a big deal for some because it takes away some readability. Lastly, all the javascript resources we included on the head of our template will definitely eat loading time. So if you're concerned with that, one way to reduce it (albeit marginally) is to remove any syntax you won't be using on your site, 'cos what's the point right.

Anyway, I guess Blogger just really isn't a friendly place for coding blogs like these. I could imagine this being super easy on Wordpress, but well, here we are! :D I'm still hoping for a better solution, something that will allow me to insert a code snippet via the Compose view, with all the fanciness of a syntax highlighter. Wait is there one already? LET ME KNOW.
Share: