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

| Views: 488
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...
highlightjs.png


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...
 BBcode
[code highlight syntax=js]
[/code]


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.

-i

Have comments or feedback on what I wrote? Please share them below! Found this useful? Consider sending me a small tip.
comments powered by Disqus
Other posts you may like...