Intro to Prettify

12-22-2012 - General Web Development - Shannon McVay - 1 Comments

Prettify is a very helpful library for giving your code snippets color and line numbers when showing them online. With Prettify, you no longer need to show plain text code snippets online!

Setup

Prettify can be found at http://code.google.com/p/google-code-prettify/. It is listed as a lightweight Javascript module and CSS library. This link contains the download for the full source and detailed read-me file. I recommend this download as it contains a great deal of additional information and the full source.

When implementing Prettify, you must include both the Javascript library and the main css file on the page that needs "prettied up":

<link href="prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="prettify.js"></script>

In order to use the library, you must also wire up the following function call on your page body's onload event:

onload="prettyPrint()"

If you are using jQuery though, this is actually not required though. All you need to do is call the function when the document is finished loading:

<script language="javascript" type="text/javascript">
$(document).ready(function () {
    //Call for prettify 
    prettyPrint();
});
</script>

Usage

After setting up the page, code snippets placed in the following will automatically be pretty printed:

<pre class="prettyprint">...</pre>

<code class="prettyprint">...</code>

Conclusion

As you notice from the scripts above (which are using prettify), your script now comes to life with color! The style sheets are easily modifiable to user your own colors for offsetting type definitions, strings, etc. Please see the documentation that comes with Prettify for more details on using the library and additional features that I didn't cover (such as the use of line numbers).

Tags :

1 Comment

  • Derrick yby April 04, 2013 @ 4:19 AM

    |

Leave a Comment