Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

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.


Did you like this post or found it useful? Considering supporting this Blog to keep its web servers running, any amount helps! Thanks!
Have comments or feedback on what I wrote? Please share them below!
comments powered by Disqus
Other posts you may like...