Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.
Notice: I'm taking a break from blogging to focus on Atari Gamer . com, check it out!

NOTE: This article is 3 years or older so its information may no longer be relevant. Read on at your own discretion! Comments for this article have automatically been locked, refer to the FAQ for more details.
I was looking for an easy to implement code highlighter for my Blog and after searching around and trying out various different ones I settled on highlight.js. My requirements were simple, it had to work with the BBcode used in Flatpress and ideally to not require much code change.

What I really liked about highlight.js is it automatically figures out the code language i.e. it's syntax and highlights accordingly, of course there is a way to force a particular language too. There is also a way to tell it not to highlight something, a feature that I use as the default option on my Blog (for backwards compatibility of old blog posts).

This is a quick jsFiddle I set up to try it out...

It worked pretty well!

To integrate this into Flatpress, I changed the BBcode plugin to have two additional parameters on the [code] block - highlight and syntax i.e. it would look like this...
[code highlight syntax=js]

If the highlight parameter is present, the 'nohighlight' class would not be used i.e. highlighting would be enabled.

The value for the syntax parameter is one of the languages from this list. I made this parameter optional so if it's left out then highlight.js will automatically detect the syntax to use.

The last change I had to do to the BBcode plugin was to add a wp_footer hook that would call the hljs.highlightBlock() method exactly as it is in the jsFiddle linked above. That ensures that the method is called just once after the page is loaded.

So if you're looking for a code highlighter that is easy to set up and integrate into your Blog, highlight.js is the way to go.


Skip down to comments...
A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. If you spot something out of place, please do let me know.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...