How to use Google Code Prettify ?

If you’ve read any of our developer blogs, you’ll have noticed our code examples are really easy to read. This is all thanks to a Google Code project called Prettify.

Prettify is an OpenSource (Apache License 2.0) javascript library which styles <code> and <pre> tags containing code examples in a wide range of languages.

How to setup & use Code Prettify

Below you can find details of how to use Prettify to make your code really stand out. The Prettify javascript library is very easy to implement and use. It pretty much does everything for you as it can guess quite well which programming languages you are showing. Full instructions are available on their Google Code Wiki page, but if you want a brief introduction, this is how easy it is to implement:

Step 1: Load the library

Google Code provide hosted scripts so you don’t even need to download it, all you need is this line in your HTML <head> tag or before </body> tag:

 <script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script> 

Step 2: Usage

Put code snippets in <pre class="prettyprint">…</pre> or <code class="prettyprint">…</code> and it will automatically be pretty printed.

 <script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?skin=desert"></script> 

Prettify looks for <pre> or <code> tags with a class of prettyprint, so you will need to put code snippets in <pre class=”prettyprint”>…</pre> or <code class=”prettyprint”>…</code> and it will automatically be pretty printed. For example:

 <code class="prettyprint">
<div id="code-example">
...your code here...
</div>
</code> 

The output of the code above then looks like this:

 <div id="code-example">
...your code here...
</div> 

In addition, you can look at the skin gallery and pick styles that suit you.

You need only add ?skin=<css_name> after js file to using. The example of use skin named “desert“:

<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?skin=desert"></script> 

Prettify is an amazing library which supports a lot of languages and I thank the coders for what they have built for us all to use. And that’s about it. There are some more instructions in the Wiki if you wanted to play around.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz