Populating code examples dynamically

For my D3 tutorial I needed to include a lot of JavaScript code for demonstration. I knew Google’s prettify library would make the code look good, but I also needed to run the JavaScript to produce the examples. I hate duplication, and with the amount of code I needed to write and display, this would be a serious problem.

Fortunately, I hit upon a cool solution using jQuery.

I gave the code blocks id attributes, then inserted empty pre tags with the “code” class and a data attribute to tie them to the appropriate script tag:

<script type="text/javascript" id="foobar">
// code goes here

<pre class="code prettyprint" data-id="foobar"></pre>

(The pre tag also has the prettyprint class for Google prettify.)

This jQuery snippet selects each pre.code element, and inserts the text of the script tag into it:

$("pre.code").each(function() { 
  $(this).html($("#" + $(this).data("id")).text().trim()); 

The text is trimmed to avoid empty lines at the beginning.

I think the results look pretty good!