Add Google Code Prettify to Your Website
Add Google Code Prettify to your website, to allow syntax highlighting of source code snippets in any web page.
Add Google Code Prettify to your website, to allow syntax highlighting of source code snippets in any web page. Google Code prettify was developed to work on any HTML generated page and works even if code contains embedded links and line numbers. Furthermore, the JavaScript module is only 14 KB minified and the style can be customized through CSS. You can specify the language through extensible language handlers. Lastly, it had good cross browser support.
I use Google Code Prettify on this website and my other websites. Google also uses it on Google Code and StackOverFlow also uses it.
Add to Your Website
Adding Google Code Prettify is as easy as three (3) steps:
CSS
Create and save a file called prettify.css
. Add the following CSS to the file, located here or use an example from the Google project itself.
Add the stylesheet to your website like this:
<link rel="stylesheet" href="prettify.css" type="text/css" media="screen" />
JavaScript
You can download and self the JavaScript module or use the hosted version provided by Google. Add one of the following to your website:
Self-Hosted:
http://prettify.js
Hosted:
https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js
Now that you have done this, you can then run the prettyPrint function once your page has finished loading. One way to do this is via the onload handler thus:
<body onload="prettyPrint()">
This is okay, but you may not want Google Code Prettify to run on every page, so you can create a JavaScript file with the following code or inline the JavaScript with the following code; this is how I do it:
!function($){$(function(){window.prettyPrint && prettyPrint()})}(window.jQuery)
Auto-Loader
You can also configure the runner through arguments. If you are using the hosted Google Code Prettify file, it’ll look something like this:
https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?lang=css&skin=sunburst
As you can see in the above example, the arguments added were: ?lang=css&skin=sunburst
Here is a table of available arguments:
Argument | Default Value | Description |
---|---|---|
autoload=(true | false) | true | run automatically on page load |
lang=… | none | Loads the language handler for the given language which is usually the file extension for source files for that language. If specified multiple times (?lang=css&lang=ml) then all are loaded. |
skin=… | none | If specified multiple times, the first one to successfully load is used. |
callback=js_ident | window.exports["js_ident"] will be called when prettyprinting finishes. If specified multiple times, all are called. |
Using Google Code Prettify
When you want to use Google Code Prettify, simply use the following HTML:
<pre class="prettyprint"> </pre>
If you want to add line numbers, use the following HTML:
<pre class="prettyprint linenums"> </pre>