Monday, 14 April 2008

Why Not - Code highlighting with Dojox

I recently stumbled across files in dojox for code highlighting and I thought why not? why not add a bit of syntactical sugar to blogger. So making use of AOL's very generous cross domain dojo hosting, I gave it a go.

You'll find info on the AOL CDN dojo releases here: http://dev.aol.com/dojo

From there we need to include the dojo core in our template using bloggers template html editor and add a tiny bit of script that looks something like this:

<script djConfig='parseOnLoad: true' src='http://o.aolcdn.com/dojo/1.1.0/dojo/dojo.xd.js' type='text/javascript'/>
<script>
dojo.require("dojox.highlight.languages.javascript");
dojo.addOnLoad(function(){
dojo.query("code").forEach(dojox.highlight.init);
});
</script>


which means when the page is finished loading, grab all the "code" blocks using dojo.query and then loop over them initialising them with dojox.highlight.init.

This is pretty much lifted from the highlight test case and is worth a look if you want to see more examples.

At this point, a little tweak to the css with the block

pre code {
display: block;
border:1px dashed #aaaaaa;
overflow:auto;
background-color:#ffffff;
color:#444444;
padding:3px;
whitespace:pre;
}

..and we have code blocks that are highlighted and will handle scrollable overflow.

For some reason, IE currently doesn't obey the 'pre' aspect of all of this and hence white spacing is lost. I'll look into that when I get a chance.

2 comments:

dante hicks said...

Awesome. I'm a blogger user for my own blog, and Never even thought about putting the AOLCDN in my headers. A note about your [script] tag though, you don't need the "invalid" djConfig="parseOnLoad:true" in this example, as you are explicity instantiating the highlight nodes in an addOnLoad function. you can combine parseOnLoad with dojoType="dojox.highlight.Code" if you want to skip the "automatic" dojo.query route. Hopefully for Dojo 1.2 I'll be able to upgrade the dojox.highlight project to the new version of highlight.js, which now does embedded detection of languages (like [style] inside of [html]) ... very exciting stuff.

I also made a prototype widget (not in CDN though) using the highlight project to turn [pre] blocks into numbered code examples, though it's not finished:

http://dante.dojotoolkit.org/dojofun/code.html

Keep it up!

Tony Issakov said...

Well spotted...Thanks :)